【问题标题】:How to call a component method from another component?如何从另一个组件调用组件方法?
【发布时间】:2017-05-19 09:06:06
【问题描述】:

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

我可以这样做吗:

这是我的标题组件:

 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

【问题讨论】:

  • 您应该将ref 属性添加到您的ComponentToDisplay 以使其至少在this.refs 下注册
  • 但老实说,您应该只更新点击状态并将其作为道具传递给您的对话框,以便它可以决定是否应该渲染。

标签: javascript reactjs


【解决方案1】:

更多这样的:

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

【讨论】:

  • 非常感谢,我被裁判弄糊涂了,但现在说得通了
  • 很高兴我能帮上忙。
猜你喜欢
  • 2020-04-05
  • 2017-08-19
  • 2019-02-03
  • 2022-08-20
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多