【问题标题】:Difference between REF and INNERREF in reactjsreactjs中REF和INNERREF的区别
【发布时间】:2020-03-19 07:36:42
【问题描述】:

我正在使用两个类组件,其中我有一个从父组件调用的方法。出于这个原因,我必须使用 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 }
         />
)
}
}

【问题讨论】:

  • innerRef 不是标准的 React 属性。它必须是Ycomponent使用的prop

标签: reactjs react-component


【解决方案1】:

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 供开发者传递引用。

欲了解更多信息,请参阅相关问题:Why, exactly, do we need React.forwardRef?

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 1970-01-01
    • 2015-06-29
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2016-09-23
    相关资源
    最近更新 更多