【问题标题】:Change value in react js on window resize在调整窗口大小时更改 React js 中的值
【发布时间】:2019-02-01 21:53:14
【问题描述】:

我正在用 react js 构建一个照片库。显然它必须是响应式的,我已经通过在组件的渲染方法中设置值来解决这个问题:

let thumbWidth = window.innerWidth >= 480 ? 75 : 100;

问题是我需要在调整窗口大小时更改 const 值。我的第一次尝试是构建一个这样的函数并将其绑定到构造函数中:

getThumbWidth = (vpWidth) => {
    if(vpWidth >= 480 ) {
        this.setState({thumbSize: 120}); 
     } else {
        this.setState({thumbSize: 50}); 
     }
}

这在设置变量的初始值方面有效,但是当窗口调整大小时如何触发该函数?

已尝试添加调整大小功能:

resize = () => this.getThumbWidth()

...然后更改 getThumbWidth 以便它设置组件状态中的值 - 想法是当状态更新时组件会自动重新渲染:

getThumbWidth = (vpWidth) => {
    if(vpWidth >= 480 ) {
        this.setState({thumbSize: 120}); 
     } else {
        this.setState({thumbSize: 50}); 
     }
}

然后按照其他几个解决方案中的建议通过生命周期方法调用它,但事件侦听器似乎没有被触发:

componentDidMount() {
    window.addEventListener('resize', this.resize)
}

componentWillUnmount() {
    window.removeEventListener('resize', this.resize)
}  

仍然无法正常工作...有什么想法吗?

【问题讨论】:

  • 仅此一项并不能解决问题,但是,如果要更改变量的值,为什么首先将其定义为constant?提示在名称中,const 是不变的 - 换句话说,不变的东西不会改变,它们保持不变。为什么不改用let - 就像const 一样充当相同的块范围变量,只有值可以更改。
  • 最好把 const 改成另一种类型
  • 谢谢 - 我发现并更改了它 - 将编辑问题以反映这一点。
  • getThumbWidth 中有一个参数但是当你调用它时你没有传递这个参数resize = () => this.getThumbWidth()

标签: javascript css reactjs responsive-design lifecycle


【解决方案1】:

@Jousi,试试下面的代码可以很好地调整窗口大小

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      windowSize: "",
      thumbWidth: 75
    };
  }

  handleResize = e => {
    const windowSize = window.innerWidth;
    const thumbWidth = (windowSize >= 480 && 100) || 75;
    this.setState(prevState => {
      return {
        windowSize,
        thumbWidth
      };
    });
  };

  componentDidMount() {
    window.addEventListener("resize", this.handleResize);
  }

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

  render() {
    return (
      <div>
        <h2>window size: {this.state.windowSize}</h2>
        <h3>thumbnail width: {this.state.thumbWidth}</h3>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

【讨论】:

  • 这个答案有误:删除事件监听器时应该使用正确的componentWillUnmount,而不是componentWillMount
【解决方案2】:

你可以给组件的容器添加 ref 属性:

return (
    <div
       className={mainClass}
       ref={(elem) => { this.elem = elem; }}
    >
        your gallery here
   </div>

然后在您的componentDidMount 中,您可以访问连接到您的容器的所有事件。然后你可以根据这些事件的变化调用你的函数。例如:

componentDidMount() {
   const parent = this.elem.parentNode;
       if (parent.scrollHeight > parent.clientHeight) {
         parent.onscroll = (() => this.yourMethod(parent));
       } 
}

【讨论】:

    【解决方案3】:

    我认为您可能需要初始化 this.resize 函数。

    像这样:window.removeEventListener('resize', this.resize())

    【讨论】:

    • 这是不正确的,你不应该调用 this.resize,你应该只是传递引用本身。
    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 2016-07-07
    • 2012-08-03
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多