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'))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值