如何从另一个组件调用一个组件方法?
我有一个包含一个按钮的标题组件,并且我希望该按钮在单击时显示另一个组件(模式页面)。
我可以做这样的事情:
这是我的标头组件:
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
-
更像这样:
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()
)。然后,在父组件中,向包含的子组件中添加一个引用,以便您可以引用它并调用该方法。