【问题标题】:Is it possible to pass a element ref from a child functional component to its parent functional component?是否可以将元素 ref 从子功能组件传递到其父功能组件?
【发布时间】:2020-04-28 19:05:07
【问题描述】:

This 帖子与我能找到的一样接近,但我仍然无法让它为 2 个功能组件工作。如果我可以回答任何进一步的问题或提供更多信息,请告诉我。非常感谢您的参与。

【问题讨论】:

  • 你给我们的链接的接受答案已经告诉你它如何与功能组件一起工作,继续阅读,如果它不起作用,那么向我们展示代码,以便我们调查你的问题:)跨度>

标签: javascript reactjs react-hooks react-ref


【解决方案1】:

在您的链接中,该答案不会导出父组件。可能这就是不在你身边工作的原因。请检查下面的导出示例。

import React, {Component} from 'react';

const Child = ({setRef}) => <input type="text" ref={setRef}/>;

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.setRef = this.setRef.bind(this);
    }

    componentDidMount() {
        // Calling a function on the Child DOM element
        this.childRef.focus();
    }

    setRef(input) {
        this.childRef = input;
    }

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

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 2021-01-26
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2020-05-27
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多