有一個主要組件,它使用菜單組件。菜單組件正在使用狀態屬性來保存關於所選菜單項的信息。但是現在我需要在主要組件中獲取選定的模塊。我怎麼做?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