在渲染函数、React Native、ES6 中选择与索引相关的值

Choose value relating to index in render function, React Native, ES6

我有一个简单的视频视图,我想做的就是将音量道具分配给一个数字,但它是一个视频数组,每个视频都有不同的音量,所以我根据视频索引创建了一个数组现在我需要每个视频都有特定的音量

var arr = [{vol: 1}, {vol: 3}, {vol: 8}]   //3 items in render
this.state = {
  volVid: arr
}

render() {
      return this.props.otherUsers.map(others =>
        <View key={others.infinite}>
          <Video
           volume={this.state.volVid}
          >
          </Video>
        </View>
      );
}

我会在 volume 道具中放置一个函数,但是它给出了一个错误,期望一个数字而不是接收一个函数,那么有没有办法进入数组并拉出特定的视频音量? 此处使用的是 Expo 视频组件。

我想你想做的是通过 .map():

上的 index 属性来引用你的 volVid 数组
render() {
  return this.props.otherUsers.map((others, index) => {
    <View key={others.infinite}>
      <Video
        volume={this.state.volVid[index].vol}
      >
      </Video>
    </View>
  });
}

根据提供的代码,您可以将索引添加到传递的回调函数中并使用它。所以:

render() {
  return this.props.otherUsers.map((others, index) =>
    <View key={others.infinite}>
      <Video
       volume={(this.state.volVid[index]) ? this.state.volVid[index].vol : 1}
      >
      </Video>
    </View>
  );
}

添加了三元检查以防万一otherUsers.length > arr.length