React 16 中的事件侦听器和引用

IT技术 reactjs
2021-05-19 01:10:04

我有一个元素,我想在渲染元素和调整父元素大小时将其宽度设置为与父元素相等。我正在使用新的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

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

1个回答

您需要使用窗口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>
    );
  }
}

演示