如何从另一个组件调用一个组件方法?

发布于 2021-01-31 22:51:10

我有一个包含一个按钮的标题组件,并且我希望该按钮在单击时显示另一个组件(模式页面)。

我可以做这样的事情:

这是我的标头组件:

 import ComponentToDisplay from './components/ComponentToDisplay/index'

 class Header extends React.Component {
  constructor(props) {
    super(props)
  }

  props : {
    user: User
  }

  _handleInvitePlayerClick = () => {
     this.refs.simpleDialog.show();
  }

  render(){

   return(
     <Button onClick={this._handleInvitePlayerClick} ><myButton/></Button>
     <ComponentToDisplay />

   )
  }
 }

这是我的模态页面组件,单击其他组件上的按钮时应显示该组件页面:

class ComponentToDisplay extends React.Component {

componentDidMount() {

}

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

用于模态的库:https :
//github.com/marcio/react-skylight

关注者
0
被浏览
81
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    更像这样:

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

    确保showMe()在子组件上公开一个方法:

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

    基本上,这是在将SkyLight的show()方法包装在子组件自己的方法中(在本例中为showMe())。然后,在父组件中,向包含的子组件中添加一个引用,以便您可以引用它并调用该方法。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看