【问题标题】:Combine method calls for onLayout合并 onLayout 的方法调用
【发布时间】:2016-04-27 23:38:33
【问题描述】:

我有一个使用 onLayout 属性的组件。但是我也想从父组件接收道具并执行给定的方法,以及内部方法。

在我的组件中

onLayout = event => { 
  const { width } = event.nativeEvent.layout;
  this.setState({ width: width });
} 

在我的渲染方法中

const { onLayout } = this.props;
return (
  <View onLayout={this.onLayout}>
  ...
  </View>
)

如何将 onLayout 与内部 this.onLayout 组合在一起?我可以创建一个新方法,但是如何处理 event 参数,同时保持 ES6 语法?

【问题讨论】:

  • 我会添加 es2015 标签。因为这似乎与问题确实相关。
  • 同时删除三个反引号以更好地格式化代码。

标签: javascript react-native ecmascript-6


【解决方案1】:

我认为创建结合两个子方法的新方法是个好方法:

onLayout = event => {
  this.props.onLayout(event);
  this.updateWidth(event); 
}

updateWidth = event => {
  const { width } = event.nativeEvent.layout;
  this.setState({ width: width });
}

在渲染中:

return (
  <View onLayout={this.onLayout.bind(this)}>
  ...
  </View>
)

【讨论】:

    【解决方案2】:

    使用函数原型的bind 方法将你的函数绑定到当前上下文:

    &lt;View onLayout={this.onLayout.bind(this)}&gt;

    【讨论】:

    • 我不明白这两种方法会如何执行?
    【解决方案3】:

    @Yuriy 的回答是一个很好的线索。

    我通过bind 传递了onLayout 作为参数:

    onLayoutInternal = (onLayout, event) => { 
      const { width } = event.nativeEvent.layout;
      this.setState({ width: width });
      onLayout(event);
    } 
    

    像这样使用绑定:

    render() {
      const { onLayout } = this.props;
      return (
        <View onLayout={this.onLayoutInternal.bind(this, onLayout)}>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多