首页 > 解决方案 > React 16 中的事件监听器和引用

问题描述

我有一个元素,我想在渲染元素和调整父级大小时将其宽度设置为等于父级。我正在使用新的React.createRefAPI 来实现这一点,目前有以下内容:

class Footer extends Component {
  constructor(props) {
    super(props);
    this.footerRef = React.createRef();
    this.state = { width: 0 };
  }

  updateWidth() {
    const width = this.footerRef.current.parentNode.clientWidth;
    this.setState({ width });
  }

  componentDidMount() {
    this.updateWidth();
    this.footerRef.current.addEventListener("resize", this.updateWidth);
  }

  componentWillUnmount() {
    this.footerRef.current.removeEventListener("resize", this.updateWidth);
  }

  render() {
    const { light, setEqualToParentWidth, className, ...props } = this.props;

    const style = setEqualToParentWidth
      ? { ...props.style, width: this.state.width }
      : { ...props.style };

    return (
      <footer
        {...props}
        ref={this.footerRef}
        style={style}
        data-ut="footer"
      />
    );
  }
}

这似乎编译没有任何错误,并且在安装时准确地调整了自身大小。但是,一旦它已安装,更改视口宽度不会更改页脚的宽度。我是否错误地附加了事件侦听器?

我最初也尝试将事件侦听器附加到window,但这导致我尝试调整屏幕大小时TypeError: Cannot read property 'current' of undefined的第一行。updateWidth

我怎样才能解决这个问题?

标签: reactjs

解决方案


您需要使用窗口resize事件。当您分配事件侦听器时,您需要绑定到构造函数内的正确范围this.updateWidth = this.updateWidth.bind(this);

这也应该去抖动。

试试这个:

class FooterBase extends Component {
  constructor(props) {
    super(props);
    this.footerRef = React.createRef();
    this.updateWidth = this.updateWidth.bind(this);
    this.state = { width: 0 };
  }

  updateWidth() {
    const width = this.footerRef.current.parentNode.clientWidth;
    this.setState({ width });
  }

  componentDidMount() {
    this.updateWidth();

    window.addEventListener('resize', this.updateWidth);
  }

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

  render() {
    const { light, setEqualToParentWidth, className, ...props } = this.props;

    const style = setEqualToParentWidth
      ? { ...props.style, width: this.state.width }
      : { ...props.style };

    return (
      <footer
        {...props}
        ref={this.footerRef}
        style={style}
        data-ut="footer"
      ></footer>
    );
  }
}

演示


推荐阅读