有一个主要组件,它使用菜单组件。菜单组件正在使用状态属性来保存关于所选菜单项的信息。但是现在我需要在主要组件中获取选定的模块。我怎么做?ReactJS:如何获得另一个组件的状态属性?
class Main extends Component {
doSomething(module) {
console.log(module) // should get 'targetValue'
// I need to get the info, which module is selected.
// This info is stored as a state value in the `MainMenu` Component
// How do I get this information? I can't use the parameter `selectModule` as it is done here.
}
render() {
return (
<div>
<MainMenu />
<Button
onClick={ this.doSomething.bind(this, selectedModule) }
/>
</div>
)
}
}
在此组件每个模块(的modules
阵列)生成的菜单。通过点击一个项目,该模块被存储到module
状态变量中。
class MainMenu extends Component {
constructor(props) {
super(props)
this.state = {
module: 'initialValue'
}
}
selectModule(module) {
this.setState({ module })
}
render() {
return (
<Menu>
<Menu.Item onClick={ this.selectModule.bind(this, 'targetValue') } >
{ title }
</Menu.Item>
</Menu>
)
}
}
维持MainMenu组件该状态值,而不是,在保持主成分并传递作为道具两个部件,并且还传递函数来MainMenu在主要组件中更新它。 –
我不明白如何从'MainMenu'组件更新状态,然后应该在'Main'组件处... – user3142695