React中ref详解+例子

2018-05-24  本文已影响0人  zhangjingbibibi

事件处理

<input onFocus={this.handleClick}/>
    handleFocus(event) {
      event.target  //返回input对象
    }

强烈注意

问题: 如何给一个函数强制指定内部的this?

   /*
    需求: 自定义组件, 功能说明如下:
      1. 界面如果页面所示
      2. 点击按钮, 提示第一个输入框中的值
      3. 当第2个输入框失去焦点时, 提示这个输入框中的值
    */
    class RefsTest extends React.Component {
      constructor (props) {
       super(props);

        this.showMsg = this.showMsg.bind(this); // 强制给showMsg()绑定this(组件对象)
        this.handleBlur = this.handleBlur.bind(this);
      }

      showMsg() {
        // console.log(this); //this默认是null, 而不组件对象
        const input = this.refs.msg;
        alert(input.value);
      }

      handleBlur(event) {
        const input = event.target;
        alert(input.value);
      }

      render () {
        return (
          <div>
            <input type="text" ref="msg"/>
            <button onClick={this.showMsg}>提示输入数据</button>
            <input type="text" placeholder="失去焦点提示数据" onBlur={this.handleBlur}/>
          </div>
        );
      }
    }

    ReactDOM.render(<RefsTest/>, document.getElementById('example'));
上一篇 下一篇

猜你喜欢

热点阅读