为什么ref在子组件中不属于属性? [英] Why is ref not a property in children components?

查看:235
本文介绍了为什么ref在子组件中不属于属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近注意到,在ReactJS中,不可能将ref作为属性传递给组件.

I've recently noticed that in ReactJS passing ref to a component as property is not possible.

这是我的代码:

class A extends React.Component{
    render(){
        return <B
            ref={ref=>this.bRef = ref} 
        />
    }
}

class B extends React.Component{
    render(){
        console.log(this.props.ref) //=>undefined
        return <div
            {...this.props}
        />
    }
}

this.bRefA中将是未定义的.请问对此有解释吗?

this.bRef will be undefined in A. Is there a explanation about this?

推荐答案

对此有解释吗?

Is there a explanation about this?

您看到的问题是由于keyref是特殊道具这一事实造成的. 请参见

The issue you are seeing is due to the fact that key and ref are special props. See

大多数JSX元素上的道具都传递给组件,但是, React有两个特殊的道具(ref和key), 因此不会转发给组件.

Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.

例如,尝试从组件访问this.props.key (即render函数或propTypes)未定义.如果你需要 要在子组件中访问相同的值,您应该传递 它可以用作其他道具(例如:<ListItemWrapper key={result.id} id={result.id} />).虽然这似乎有些多余,但重要的是 将应用逻辑与协调提示分开.

For instance, attempting to access this.props.key from a component (i.e., the render function or propTypes) is not defined. If you need to access the same value within the child component, you should pass it as a different prop (ex: <ListItemWrapper key={result.id} id={result.id} />). While this may seem redundant, it’s important to separate app logic from reconciling hints.

要访问子级中的ref,请以其他方式传递它. 假设您创建了一个ref类似

To access ref in child pass it in a different prop. Say you create a ref like

const ref = React.createRef();

,然后将其传递到组件,如下所示:

and then you pass it to your component as shown below:

<FancyButton forwardedRef={ref} text="Click ME!" />

FancyButton内部的引用将以

 <button
      onClick={() => {
        this.logRef(forwardedRef);
      }}
      ref={forwardedRef}
    >
      {text}
 </button>

其中logRef定义为

logRef(myref) {
    console.log(myref.current);
}

可以在(单击按钮并检查控制台)上看到一个工作示例: https://codesandbox .io/s/ko6wnrorv

a working example can be seen at (Click on the button and check the console) : https://codesandbox.io/s/ko6wnrorv

这篇关于为什么ref在子组件中不属于属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆