【发布时间】:2016-04-08 11:04:01
【问题描述】:
我有一个 React 应用程序,其中有一个事件侦听器,用于调整窗口对象的大小事件。
class App extends React.Component {
constructor(props){
super(props);
this.state = { width: 0 }
this.setSize = this.setSize.bind(this);
}
render() {
let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
return(<div>{content}</div>)
}
setSize() {
this.setState({
width: window.innerWidth
});
}
componentDidMount() {
this.setSize();
window.addEventListener('resize', this.setSize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.setSize);
}
}
这东西有效,但我的问题是我不知道如何访问子组件内的 App 组件的状态(窗口宽度)。
那么,有人可以解释一下如何在我的子组件中访问/发送 this.state.width(我知道我可以使用道具发送,但是如果我还有 2 个组件呢?)
【问题讨论】:
-
可以通过 props 发送给多个子组件。
标签: javascript reactjs