关于 React Refs

只愿长相守 提交于 2019-11-26 16:35:40

一、什么是 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”在控制台输出: 

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!