简体   繁体   中英

React Native - How to get key for array mapped components

I created this simple 'Base' component which dynamically creates multiple 'Box' components (via renderBoxes() method). When one of these box components is pressed, I want to know which one among all the dynamically created Box component is pressed. Is there a way for that? Are we gonna we use the 'key'?

import data from './dataFile.json';

class Base extends Component {

  state = {calendarData: []};

  componentWillMount() {
    //storing json data in the state
    this.setState({ calendarData: data });
  }

  onBoxPress() {

    // HOW TO ACCESS WHICH BOX COMPONENT WAS PRESSED?

  }   

  renderBoxes() {
    return this.state.calenderData.map(ride => {
      <Box
        key={ride.id}
        onPress={this.onBoxPress}>
      </Box>
    });
  }

  render() {
    return(
      <View>
        { this.renderBoxes() }
      </View>
    );
  }
}

Please provide a short reason as well. Thanks.

The key prop is used internally by React to optimise the virtual rendering. While it could be used to pass information back to the parent, it probably shouldn't. (In fact, in dev mode I think you'll get a warning if you try to access the key prop.)

Instead, you can wrap the onPress callback in an anonymous function that closes over the ride variable:

  <Box
    key={ride.id}
    onPress={() => this.onBoxPress(ride)}>
  </Box>

You can then receive the ride in the onBoxPress callback:

onBoxPress(ride) {
  // do something with the ride
}  

Edit:

Using an anonymous function wrapper has the additional benefit that is binds the this context of the callback function correctly. If you don't use a wrapping function, you'd have to bind it manually:

  <Box onPress={this.onBoxPress.bind(this)}></Box>

Alternatively, to auto-bind the this context you can use the class property syntax instead:

onBoxPress = () => {
  // `this` is now bound correctly
  this.setState(...)
}  

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