简体   繁体   中英

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

This post is as close as I could find, but I am still unable to get it working for 2 functional components. Please let me know if I can answer any further questions or provide more information. Thank you so much for your time.

In your link, That answer does not export the Parent Component. May be that is the reason for not working in your side. Please check the below example with export.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM