zoukankan      html  css  js  c++  java
  • React ref回调函数例子

    ref属性也可以是一个回调函数而不是一个名字。   这个函数将要在组件被挂载之后立即执行。

    这个参照的组件将会作为该函数的参数,这个函数可以立即使用这个组件参数,当然也可以将其保存供以后使用。

    当这个参照组件被卸载并且这个ref改变的时候,先前的ref的参数值将为null。这将有效的防止了内存的泄露。

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="react.js"></script>
    <script src="react-dom.js"></script>
    <script src="browser.min.js"></script>
    </head>
    <body>
    <div id="#root">

    </div>


    </body>
    <script type="text/babel">
    window.onload = function(){
    class Main extends React.Component{
    constructor(){
    super();
    this.textChange = this.textChange.bind(this);
    this.clearText = this.clearText.bind(this);
    this.state = {"con":"你好"}
    }
    textChange(e){
    this.setState({
    "con":e.target.value
    })
    }
    clearText(e){
    this.setState({
    "con":""
    })
    }
    render(){
    return(<div>
    <input type="text" value={this.state.con} onChange={this.textChange} ref={function(input){ alert(input);if(input!=null){input.focus()}}} />
    <input type="button" value="清空并获得焦点" onClick={this.clearText} />
    <input type="text" />
    </div>)
    }
    }
    ReactDOM.render(<Main/>,document.getElementById('#root'))
    }

    </script>
    </html>

    return(<div>
    <input type="text" value={this.state.con} onChange={this.textChange} ref={function(input){ alert(input);if(input!=null){input.focus()}}} />
    <input type="button" value="清空并获得焦点" onClick={this.clearText} />
    <input type="text" />
    </div>)

    第一次打开页面时会弹出[object HTMLInputElement];

       这个函数将要在组件被挂载之后立即执行。

    当点击按钮时则会弹出两个对话框

        一个为 null

        另一个为[object HTMLInputElement]

    为什么弹出两次呢?

    第一次因为ref回调函数会在ref改变时触发,且ref参数的值为null,所以弹出null

    第二次因为调用clearText函数改变state会重新渲染改变的组件,所以再次弹出[object HTMLInputElement]

     

        

  • 相关阅读:
    Silverlight Control(五)TimePicker
    《ASP.NET Core 3框架揭秘》笔记
    Hyper-V初体验
    debian初体验
    异步编程-编程指南
    Oracle查询优化读书笔记
    设计原则
    日志管理
    Git在Vs中的使用
    SVN使用备注
  • 原文地址:https://www.cnblogs.com/qdcnbj/p/8391329.html
Copyright © 2011-2022 走看看