How to call a component method from another component?

后端 未结 1 1015
被撕碎了的回忆
被撕碎了的回忆 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 (
                
                
            )
        }
    }
    

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

    class ComponentToDisplay extends React.Component {
    
        showMe() {
            this.refs.simpleDialog.show();
        }
    
        render() {
            return (
                
    {"Text inside the modal."}
    ) } }

    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)
提交回复
热议问题