react中refs的理解

react中refs的理解

在react中refs的作用与vue中类似,都是用于对元素做标记以便于获取并修改DOM元素

注意:ref在原生DOM元素上和自定义组件上是不同的,ref在原生DOM元素上获取到的是DOM元素本身,而在自定义组件当中,ref获取到的是组件的子组件

目前较常用ref使用方式有两种
方式一:使用回调函数的形式

class RefExample extends React.Component{
  constructor(props){
    super(props);
    this.func = this.func.bind(this)
  }
  func(){
    this.dom.style.color = 'green'
  }
  render(){
    return (
      /* 回调函数中的参数为当前绑定的DOM对象,点击触发事件将按键字体颜色改为绿色,就是你头上的那个绿色 */
      <button ref={(dom)=>{this.dom = dom}} onClick={this.func}>Click me!</button>
    )
  }
}
ReactDOM.render(<RefExample/>,document.getElementById('root'))

方式二:使用react16后新增的createRef()的方式创建Ref然后将其挂载到DOM上

class RefExample extends React.Component{
  constructor(props){
    super(props);
    this.func = this.func.bind(this)
    // 1、创建ref对象
    this.myRef = React.createRef();
  }
  func(){
    // 3、获取元素并修改属性
    this.myRef.style.color = 'green'
  }
  render(){
    return (
      // 2、将ref对象挂载到dom元素上
      <button ref={this.myRef} onClick={this.func}>Click me!</button>
    )
  }
}
ReactDOM.render(<RefExample/>,document.getElementById('root'))

Refs转发

官方说法:Ref 转发是一项将 ref 自动地通过组件传递到其一子组件的技巧
实际上就是在父组件通过ref可以获取到子组件的元素

class RefExample extends React.Component{
  constructor(props){
    super(props);
    // 3、父组件通过转发将ref转发到子组件
    const FancyButton = React.forwardRef((props,ref) => {
      // 4、子组件挂载ref
      <button ref={ref}>
        {props.children}
      </button>
    })
    // 1、创建ref
    this.myRef = React.createRef();
  }
  render(){
    return (
      // 2、将ref对象挂载到dom元素上
      <FancyButton ref={this.myRef}>Click me!</FancyButton>
    )
  }
}
ReactDOM.render(<RefExample/>,document.getElementById('root'))

你可能感兴趣的:(react)