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

时间:2017-01-04 22:52:12

标签: javascript reactjs

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

我可以这样做:

这是我的标题组件:

 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

1 个答案:

答案 0 :(得分:4)

更像这样:

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())。然后,在您的父组件中,为您包含的子组件添加一个引用,以便您可以引用它并调用该方法。

相关问题