簡體   English   中英

是否可以將元素 ref 從子功能組件傳遞到其父功能組件?

[英]Is it possible to pass a element ref from a child functional component to its parent functional component?

這篇文章與我能找到的一樣接近,但我仍然無法讓它適用於 2 個功能組件。 如果我可以回答任何進一步的問題或提供更多信息,請告訴我。 非常感謝您的參與。

在您的鏈接中,該答案不會導出父組件。 可能這就是不在你身邊工作的原因。 請檢查下面的導出示例。

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}/>
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM