小编典典

根据视口大小有条件地做出反应

reactjs

对于您来说,这对React
Monsters来说应该是一件容易的事。:)我已经写了条件,但是我不知道如何在构造函数中处理视口大小以使条件起作用。简单明了,我想在视口大小为1451px或更宽时显示一个元素,而在1450px或更小时显示另一个元素。

这是我的代码(简体)

class My Class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isDesktop: "1450px" //This is where I am having problems
        };
    }

    render() {
        const isDesktop = this.state.isDesktop;

        return (
            <div>
                {isDesktop ? (
                    <div>I show on 1451px or higher</div>
                ) : (
                    <div>I show on 1450px or lower</div>
                )}
            </div>
        );
    }
}

也许我应该将其与ComponentWillMount或ComponentDidMount一起使用。老实说,不确定。我是React的新手。

在此先感谢大家。


阅读 196

收藏
2020-07-22

共1个答案

小编典典

也许我应该将其与ComponentWillMount或ComponentDidMount一起使用

是的,您需要侦听resize事件并在更改时更新内部状态。您可以通过在组件安装时添加事件处理程序来实现。在这里尝试完整的示例。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isDesktop: false //This is where I am having problems
    };

    this.updatePredicate = this.updatePredicate.bind(this);
  }
  componentDidMount() {
    this.updatePredicate();
    window.addEventListener("resize", this.updatePredicate);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.updatePredicate);
  }

  updatePredicate() {
    this.setState({ isDesktop: window.innerWidth > 1450 });
  }

  render() {
    const isDesktop = this.state.isDesktop;

    return (
      <div>
        {isDesktop ? (
          <div>I show on 1451px or higher</div>
        ) : (
          <div>I show on 1450px or lower</div>
        )}
      </div>
    );
  }
}
2020-07-22