我这样做是为了以这种方式调用兄弟姐妹方法(状态):
应用程序.js
class App extends Components {
onClick(){
/*.. calulate total..*/
this.setState({
total: window.totalValue
})
}
render() {
return (
<Main>
{/*..*/}
<Body onClick={this.onClick}/>
<Footer total={this.state.total} />
</Main>
);
}
}
class Body extends Components {
onClick(){
this.props.onClick();
}
render(){
return <Section onClick={this.onClick} />
}
}
class Section extends Components{
render(){
return (
<button onClick={props.onClick}>Calculate</button>
)
}
}
class Footer extends Components{
render(){
return props.total;
}
}
但是当有更多子组件时,很难继续将道具传递给每个子组件。做这样的事情可以吗?
管理器.js
const Components = {}
export const connect = ( obj ) =>{
Components[obj.constructor.name] = obj;
return obj;
}
export const manager = () => {
return Components;
}
并 in<Footer/>的构造函数传递this给connect函数以保存其引用:
/*...*/
constructor(props){
super(props)
connect(this) // saving component reference to call its method later.
}
/*...*/
和 in <Section/>, addonClick和 in <Footer/>addcalculateTotal方法是这样的:
/*.. Section ..*/
onClick(){
manager().Footer.calculateTotal();
}
/*.. Footer ..*/
calculateTotal(){
this.setState({
total: window.totalValue
})
}
render(){
return this.state.total;
}
后来的方法只是设置状态<Footer/>而不是传递值的形式,当最深的孩子的状态被调用时<Main/>,我们不必调用每个方法(状态)。onClick
提前感谢您的回答。