猿问

数组map()接收[object Object]而不是item

我的目的是在一行中渲染5个星星:


constructor(props) {

    super(props);

    this.state = {

        selectedStar: '',

        ...

    };


    this.starsArray = [1, 2, 3, 4, 5] // is used like indexes

}


onStarPress = (index) => {

    console.warn('index = ' + index); // index here is [object Object] instead of 1, 2, 3 ...

    this.setState({

        selectedStar: index

    });

}


renderStars = () => (

    this.starsArray.map((starIndex, i) => (

        <Star

            key = {i}

            color = {this.defineStarColor(starIndex)}

            onStarPress = {(starIndex) => {this.onStarPress(starIndex)}}

        />

    ))

)

当我map()对索引数组执行starIndex等于[object Object]而不是1、2、3 ...


i这里等于1,2 ...与key。但是当我将其传递给下面的函数时,它也变成[object Object]


我做错了什么?


元芳怎么了
浏览 210回答 2
2回答

开满天机

在这一行中onStarPress = {(starIndex) => {this.onStarPress(starIndex)}},第一个starIndex是事件处理对象。onStarPress接收对象也是如此。有两种方法可以解决此问题:onStarPress = (e,index) => {&nbsp; &nbsp; console.warn('e = ' + e);&nbsp;&nbsp; &nbsp; console.warn('index = ' + index);&nbsp;&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; selectedStar: index&nbsp; &nbsp; });}renderStars = () => (&nbsp; &nbsp; this.starsArray.map((starIndex, i) => (&nbsp; &nbsp; &nbsp; &nbsp; <Star&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={i}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color={this.defineStarColor(starIndex)}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onStarPress={(e) => { this.onStarPress(e,starIndex) }}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; )))其他方式是:onStarPress = (index) => (e) => {&nbsp; &nbsp; console.warn('e = ' + e);&nbsp;&nbsp; &nbsp; console.warn('index = ' + index);&nbsp;&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; selectedStar: index&nbsp; &nbsp; });}renderStars = () => (&nbsp; &nbsp; this.starsArray.map((starIndex, i) => (&nbsp; &nbsp; &nbsp; &nbsp; <Star&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={i}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color={this.defineStarColor(starIndex)}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onStarPress={this.onStarPress(starIndex)}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; )))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答