Javascript 用于onLayout的组合方法调用

Javascript 用于onLayout的组合方法调用,javascript,react-native,ecmascript-6,Javascript,React Native,Ecmascript 6,我有一个使用onLayout属性的组件。但是,我还希望从父组件接收prop,并执行给定的方法以及内部方法 在我的组件中,我有 onLayout = event => { const { width } = event.nativeEvent.layout; this.setState({ width: width }); } 在渲染方法中,我有 const { onLayout } = this.props; return ( <View onLayout={thi

我有一个使用
onLayout
属性的组件。但是,我还希望从父组件接收prop,并执行给定的方法以及内部方法

在我的组件中,我有

onLayout = event => { 
  const { width } = event.nativeEvent.layout;
  this.setState({ width: width });
} 
在渲染方法中,我有

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

如何将
onLayout
道具与内部
this.onLayout
组合?我可以创建一个新方法,但如何处理
事件
参数,保持ES6语法?

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


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


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

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

onLayoutInternal = (onLayout, event) => { 
  const { width } = event.nativeEvent.layout;
  this.setState({ width: width });
  onLayout(event);
} 
像这样使用bind:

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

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

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

onLayoutInternal = (onLayout, event) => { 
  const { width } = event.nativeEvent.layout;
  this.setState({ width: width });
  onLayout(event);
} 
像这样使用bind:

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

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

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>
)
返回(
...
)

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

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>
)
返回(
...
)

我想添加es2015标签。因为这似乎与问题非常相关。同时删除三个回勾以更好地格式化代码。我会添加es2015标记。因为这似乎真的与问题有关。还要删除三个回勾以更好地格式化代码。我不明白这将如何执行这两个方法?我不明白这将如何执行这两个方法?