Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

forwardRef如何在两个Component组件用?

子组件

class ChildComponent extends React.Component {

    logc = () => {
        console.log('---child---')
    }

    render() {
        return <div>ChildComponent</div>
    }
}

export default ChildComponent

父组件

class ParentComponent extends React.Component {

    constructor(props) {
        super(props);
        console.log('p-custructor', props);
    }

    logp = () => {
        console.log('---parent---')
    }

    render() {
        return <div>ParentComponent<ChildComponent ref={this.props.ref} /></div>
    }
}

export default React.forwardRef((props, ref) => (<ParentComponent ref={ref} />));

页面

class Demo extends React.Component {
    parentRef: React.RefObject<any>;

    constructor(props: any) {
        super(props);
        this.parentRef = React.createRef();
    }

    handleClick = () => {
        console.log('this.parentRef', this.parentRef);
    }

    render() {
        return (
            <div className={styles.container}>
                <Button type="primary" onClick={this.handleClick}>click</Button>
                <ParentComponent ref={this.parentRef} />
            </div>
        );
    }
}

handleClick中的parentRef还是父组件的实例,如何在页面中拿到子组件的Ref???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

forwardRef 需要在子组件再包一层


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...