关于 React Refs

一、什么是 ref

React 提供了 ref 属性,用来对元素进行 DOM 操作

二、使用 ref 的方式

1、字符串模式

绑定 ref 属性 XX,通过 this.refs.XX 获取

class refTest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  handleClick() {
    console.log(this.refs.inputElem.value)
  }

  render() {
    return (
      <React.Fragment>
      <div>
        <input type="text" ref="inputElem" />
      </div>
      <button onClick={this.handleClick.bind(this)}>toConsole</button>
      </React.Fragment>
    )
  }
}

字符串模式不支持静态类型检测,且 React 不建议使用

2、回调函数模式

在 ref 属性中设置回调函数,通过 this.XX 获取

class refTest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  handleClick() {
    console.log(this.inputElem.value)
  }

  render() {
    return (
      <React.Fragment>
      <div>
        <input type="text" ref={(input) => this.inputElem = input} />
      </div>
      <button onClick={this.handleClick.bind(this)}>toConsole</button>
      </React.Fragment>
    )
  }
}

运行结果:

点击“toConsole”在控制台输出: 

回调函数模式支持静态类型检测

猜你喜欢

转载自www.cnblogs.com/Leophen/p/11326600.html