将事件信息作为道具传递给子组件

时间:2016-01-29 15:38:51

标签: reactjs react-native

我想将父组件的高度传递给它的一个子组件。我最终成功地将event.nativeEvent.layout.height保存在父级的状态中并将其作为道具传递给孩子(此处:mySubComponent2)。

但是,由于父级的高度在渲染后不会改变,我认为高度应该是道具。如何将myHeight作为道具传递给MySubComponent2? 这是我尝试过的,不起作用的东西:

render: function() {
  return (
    <View onLayout={(event) => {
      var myHeight = event.nativeEvent.layout.height;
    }}>
      <MySubComponent1 />
      <MySubComponent2 parentHeight={this.myHeight} />
    </View>
  );
},

我真正想做的是有两个flexDirection:&#39;列&#39;在flexDirection中:&#39; row&#39;查看并让两个子组件具有相同的长度,例如如下图所示:

two_columnDirection_components_in_rowDirection_comp

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情来实现你所寻求的(测试):

getInitialState() {
  return {
    height:0
  }
},

measure() {
  this.refs.mycomponent.measure((a, b, width, height) => {
    this.setState({ height })
   })
},

<View ref="mycomponent" style={{ height: 300 }} onLayout={ () => this.measure() }>
  <MySubComponent2 parentHeight={this.state.height} />
</View>
相关问题