简体   繁体   中英

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

I have a simple video view and all I want to do is assign the volume props to a number however it's an array of videos and each video has a different volume, so I created an array based on the index of videos now I need each video to have it's specific volume

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>
      );
}

I would have put a function inside the volume props however it gave an error of expecting a number and instead receiving a function, so is there a way to reach into the array and pull the specific video volume? Expo video component being used here.

I think what you're trying to do is to refer to your volVid array through index prop on .map() :

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

Based on the code provided, you can just add the index to the passed callback function and use that. So:

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>
  );
}

Added a ternary check just in case otherUsers.length > arr.length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM