怎么把commentLists中的index傳遞到APP.js中
commentsList.js?handleDelete(index){console.log(index)this.props.delete(index);}render?(){const?{comments}?=?this.props;return?(<div?className="comment-list-compenent"><label>評論列表</label><ul?className="list-group?mb-3">{comments.map((comment,?index)?=><likey={index}className="list-group-item"onClick?=?{this.handleDelete}index?=?{index}>{comment}</li>)}</ul></div>)}DeleteItem(index){
const list = [...this.state.comments];
list.splice(index, 1);
this.setState({
comments: list //如果key和值是一樣的直接寫一個就行了
});
}
2019-10-11
這里有一個很關鍵的地方需要注意。子組件純函數是沒有this 的,所以通過
是無法調用的。正確的方法應該是在子組件純函數的頭部引入父組件的:函數名、參數變量,如下:
const?CommentList?=?({comments,onDeleteThis})?=>?{}這個時候,才能在子組件的純函數內使用:
2019-03-06
你這沒有把index傳出去啊,可以用箭頭函數
onClick={()=>{this.props.deleteComment(index)}}App.js中
<CommentList ????comments={comments} ????deleteComment={this.deleteComment} />deleteComment(index){ ??let?newComments=this.state.comments; ??newComments.splice(index,1); ??this.setState({ ????comments:newComments ??}) }