代码之家  ›  专栏  ›  技术社区  ›  user567

在react native中未调用onLayout

  •  0
  • user567  · 技术社区  · 8 年前

    我试图用这个代码检测宽度的变化

    class MyClass extends Component {
      onLayout(event) {
        const {x, y, height, width} = event.nativeEvent.layout;
        const newHeight = this.state.view2LayoutProps.height + 1;
        const newLayout = {
            height: newHeight ,
            width: width,
            left: x,
            top: y,
          };
    
        this.setState({ view2LayoutProps: newLayout });
        alert('ok');
      }
    

    the the the onLayout 从未调用函数。代码有问题吗?我在这个网站上找到了代码。

    1 回复  |  直到 8 年前
        1
  •  5
  •   Atticus    8 年前

    你有没有加上 onLayout MyClass React.Component 实例(如 componentDidMount ),这是一个事件 来自另一个组件 您可以通过提供 在线布局 回调 属性。这是 react-native 内置组件。

    class MyClass extends Component {
      onLayout(event) {
        const {x, y, height, width} = event.nativeEvent.layout;
        const newHeight = this.state.view2LayoutProps.height + 1;
        const newLayout = {
            height: newHeight ,
            width: width,
            left: x,
            top: y,
          };
    
        this.setState({ view2LayoutProps: newLayout });
        alert('ok');
      }
    
      render() {
        return (
          <View onLayout={e => this.onLayout(e)} />
        )
      }
    }
    
    推荐文章