How to call a component method from another component?

后端 未结 1 987
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 05:36

I have a header component that contain a button and I want this button to display another component(modal page) when it\'s clicked.

Can I do something like this:

相关标签:
1条回答
  • 2021-01-07 06:26

    More like this:

    class Header extends React.Component {
        constructor(props) {
            super(props)
        }
    
        props: {
            user: User
        }
    
        render() {
            return (
                <Button onClick={() => this.refs.componentToDisplay.showMe()}><myButton /></Button>
                <ComponentToDisplay ref="componentToDisplay" />
            )
        }
    }
    

    Being sure to expose a showMe() method on your child component:

    class ComponentToDisplay extends React.Component {
    
        showMe() {
            this.refs.simpleDialog.show();
        }
    
        render() {
            return (
                <div>
                    <SkyLight
                        ref="simpleDialog"
                        title={"Title for the modal"}>
                        {"Text inside the modal."}
                        <Button onClick={() => this.refs.simpleDialog.hide()}>{"Close modal"}</Button>
                    </SkyLight>
                </div>
            )
        }
    }
    

    Basically, what's going on here is you wrap the SkyLight's show() method in your child component's own method (in this case, showMe()). Then, in your parent component you add a ref to your included child component so you can reference it and call that method.

    0 讨论(0)
提交回复
热议问题