【问题标题】:React resize change componentsReact 调整大小更改组件
【发布时间】: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


【解决方案1】:
      render() {
        let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
        return(<div>
            <div>{content}</div>
            <childComponent myWidth= {this.state.width}></childComponent >
            <childComponent2 myWidth= {this.state.width}></childComponent2 >
       </div>
      )
 }

【讨论】:

  • 谢谢你的回答,如果childComponent有childComponent我也应该添加props吗?这是一个好习惯吗?
  • 是的。你可以。如果一个子组件有子组件,那么也遵循相同的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 2016-09-01
  • 2013-01-16
  • 2011-11-08
相关资源
最近更新 更多