reactjs中REF和INNERREF之间的区别

时间:2019-11-23 12:31:58

标签: reactjs react-component

我正在使用两个类组件,其中有一个我要从父组件调用的方法。由于这个原因,我必须使用React.CreateRef()创建两个引用。但是问题是一个组件允许我使用ref属性和onther innerRef属性。所以我想知道差异。

class X extends Component {
  constructor(props) {
    super(props);

    this.xRef = React.createRef();
    this.yRef = React.createRef();
  }

render (){
 return (
        <Xcomponent
            classes={classes}
            user={user}
            ref={this.xRef }
         />
        <Ycomponent
            classes={classes}
            user={user}
            innerRef={this.xRef }
         />
)
}
}

1 个答案:

答案 0 :(得分:0)

innerRefcomponent instance property,而refcomponent instance attribute

  

当ref属性是一个回调函数时,该函数将接收基础的DOM元素或类实例。

// Access reference within the parent component: this.xRef.current
// Access property within the component: this.props.innerRef.current
<Ycomponent ref={this.xRef} innerRef={this.xRef} />


// coolRef is an ordinary component property, you can name it as you like
<Ycomponent ref={this.xRef} coolRef={this.xRef} />
// access with this.props.coolRef.current within the component.

最后,自定义组件Ycomponent为开发人员定义了属性innerRef,以便开发人员将引用与之一起传递。