[英]React JS call function within another component
我正在嘗試使用Mousetrap庫從React的另一個組件中調用一個函數。
class Parent extends React.Component {
constructor() {
super();
}
...
render() {
return(...);
}
}
class Child extends React.Component {
constructor() {
super();
this.state = { show: false };
this.open = this.open.bind(this);
this.close = this.close.bind(this);
}
open() {
this.setState({ show: true });
}
close() {
this.setState({ show: true });
}
render() {
return(...);
}
}
現在,我想做的就是調用Mousetrap.bind('e', function(e) { Child.open() });
父級中的某個位置(因為將渲染父級,而僅在此命令上渲染子級)。 但是,我不確定該在哪里實際包括在內。 最好在構造函數中,在render()
某個地方或我未曾考慮的其他地方調用它嗎?
最好讓它成為您狀態的一部分,例如
class Parent extends React.Component {
constructor(){
super();
this._eKeyPress = this._eKeyPress.bind(this);
this.state.showChild = false;
}
componentDidMount(){
Mousetrap.bind('e', this._eKeyPress);
}
componentWillUnmount(){
Mousetrap.unbind('e', this._eKeyPress);
}
_eKeyPress(){
this.setState({showChild: true});
}
render(){
return <Child show={this.state.showChild} />;
}
}
此后的下一個問題是,是否還需要創建子項,因為您也可以這樣做
render(){
return this.state.showChild ? <Child /> : null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.