【问题标题】:React - How to pass `ref` from child to parent component?React - 如何将`ref`从子组件传递给父组件?
【发布时间】:2017-08-16 06:20:58
【问题描述】:

我有一个父组件和一个子组件,我想在我的父组件中访问子组件中的元素的ref。可以用props传递吗?

// Child Component (Dumb):
export default props =>
    <input type='number' ref='element' />

// Parent Component (Smart):
class Parent extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        const node = this.refs.element; // undefined
    }

    render() {
        return <Dumb { ...this.props }/>
    }
}

【问题讨论】:

标签: reactjs redux ref


【解决方案1】:

你可以使用callback syntax for refs:

// Dumb:
export default props =>
    <input type='number' ref={props.setRef} />

// Smart:
class Parent extends Component {
    constructor(props) {
        super(props);
    }

    setRef(ref) {
        this.inputRef = ref;
    }

    render(){
        return <Dumb {...this.props} setRef={this.setRef} />
    }
}

【讨论】:

  • 我更喜欢使用回调而不是将 ref 传递给子组件,因为您持有对父组件的引用。对于简单的组件可以正常工作,但对于大型/复杂的组件,根据最佳实践,您应该使用回调。
  • @Timo 还有没有办法在 Dumb 组件中引用 ref ?
  • @timo 在 Dumb 组件中使用 ref,这只适用于 dom 元素,Dumb 组件没有实例,这就是他将 DOM 发送到 Dumb 给父组件的原因。
  • 如何在&lt;Dumb&gt; 组件中将onChange() 赋予&lt;input&gt; 并在父组件的onChange 函数定义中获取ref
【解决方案2】:

使用 react^16.0.0,您将使用 React.createRef()。使用@Timo 的答案,它看起来像这样:

// Dumb:
export default props =>
    <input type='number' ref={props.setRef} />

// Smart:
class Parent extends Component {
    constructor(props) {
        super(props);
        this.ref1 = React.createRef()
    }

    render(){
        return <Dumb {...this.props} setRef={this.ref1} />
    }
}

【讨论】:

    【解决方案3】:

    根据DOC

    你不能在功能组件上使用 ref 属性,因为 他们没有实例。您应该将组件转换为类 如果您需要对它的引用,就像您需要生命周期时所做的那样 方法或状态。

    所以我想,如果你想使用ref,你需要使用class

    检查这个:https://github.com/facebook/react/issues/4936

    【讨论】:

    • 由于 react 钩子,特别是 useRef 钩子,情况不再如此。
    【解决方案4】:

    如果您需要动态引用,因为您有一个数组或其他东西,就像我一样。这是我在阅读上述答案后得出的结论。

    这还假设myList 是一个具有key 属性的对象数组。反正你明白了。

    此外,此解决方案在 TypeScript 中也没有任何问题。

    const Child = props => <input ref={refElem => setRef(props.someKey, refElem)} />
    
    class Parent extends Component {
    
        setRef = (key, ref) => {
          this[key] = ref; // Once this function fires, I know about my child :)
        };
    
        render(){
            return (
              {myList.map(listItem => <Child someKey={listItem.key} setRef={this.setRef} />)}
            )
        }
    }
    

    无论如何希望这对某人有所帮助。

    【讨论】:

    • 我有类似的问题,但是如何在 react v17 中使用 useRef() 来完成??
    猜你喜欢
    • 1970-01-01
    • 2022-07-15
    • 2020-10-10
    • 2020-10-21
    • 2018-12-28
    • 2020-03-30
    • 1970-01-01
    • 2022-11-24
    • 2021-05-28
    相关资源
    最近更新 更多