javascriptreact-nativetouchablehighlight

Require() in react native


I work on an idea of select star and I'm stuck on a problem. Here is my code :

export default class Star extends Component {
    render() {
        var starArray = [];
        var i;
        for (i = 0; i < 4; ++i) {
            if (i < this.props.value) {
                imageSource = this.props.fullStar;
            } else {
                imageSource = this.props.emptyStar;
            }
            starArray.push(
            <View key={i}>
                <TouchableHighlight onPress={() => console.log("etoile : "+this.key)}>
                    <Image source={imageSource} style={{width: 25, height: 25}}/>
                </TouchableHighlight>
            </View>
              );
        }
        return (
            <View style={Styles.container}>
                {starArray}
            </View>
        );
    }
}

I would like when we press on a star to know what star is pressed, my stars are in an array and I don't know what star I pressed.

it is the rendering


Solution

  • Pass the star number with the click callback.

    export default class Star extends Component {
        handleClick(i){
            console.log("star number " + i);
        }
        render() {
            var starArray = [];
            var i;
            for (i = 0; i < 4; ++i) {
                if (i < this.props.value) {
                    imageSource = this.props.fullStar;
                } else {
                    imageSource = this.props.emptyStar;
                }
                starArray.push(
                <View key={i}>
                    <TouchableHighlight onPress={this.handleClick.bind(this,i)}>
                        <Image source={imageSource} style={{width: 25, height: 25}}/>
                    </TouchableHighlight>
                </View>
                  );
            }
            return (
                <View style={Styles.container}>
                    {starArray}
                </View>
            );
        }
    }