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

问题描述 投票:0回答:1

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

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"
      />
    );
  }
}

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

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

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

reactjs
1个回答
2
投票

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

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.