从<view>数组中每个子节点的父节点调用方法

时间:2018-03-28 07:15:17

标签: javascript reactjs react-native

这是React Native(JSX)。

我有父子组件。父组件包含子组件的数组。在某些时候我需要暂停子组件,所以我需要从每个组件中调用某个方法。 这就是我尝试这样做的方式:

<View style={styles.fruits}>
      {this.state.fruitComponentArray.map((index, value) => (
        <Fruit key={index} style={styles.fruit}
          onStopAnimation={_ => this.deleteElementFromFruitArray(index)}
          onSendCoordinates={(x, y) => this.checkCoordinates2(x, y, value)}
          onRef={ref => (this.child = ref)} 
        />
      ))}
    </View>

并使用按钮调用功能:

<TouchableOpacity onPress={_ => this.child.onPause()}>

然后在子组件中有onPause()函数。

我知道问题在于引用命名,因为我总是发送一个引用,它只引用最后一个子组件。因此,不是暂停所有水果,而是暂停最后一个水果,但我不知道如何解决它。

编辑:

在下面的程序员的帮助下,这就是它最终的样子并且它可以工作: 我在构造函数

中有这个
this.child = [];

此方法(新):

 callChildrenMethods = () => {
for(var i=0; i<this.state.fruitComponentArray.length; i++){
  this.child[i].onPause();
}

}

观点数组:

    <View style={styles.fruits}>
      {this.state.fruitComponentArray.map((index, value) => (
        <Fruit key={index} style={{flex:1, position: 'absolute' , height: `${ this.state.heights[index] }%`}}
          onStopAnimation={_ => this.deleteElementFromFruitArray(index)}
          onSendCoordinates={(x, y) => this.checkCoordinates2(x, y, value)}
          onRef={ref => (this.child[index] = ref)}
        />
      ))}
    </View>

最后onClick:

 <TouchableOpacity onPress={_ => this.callChildrenMethods()}>

1 个答案:

答案 0 :(得分:0)

尝试创建包含所有引用的ref数组, 这样做了 onRef = {ref =&gt; (this.child = ref)} 试试这个 onRef = {ref =&gt; (this.child [index] = ref)} 这可能是技巧