且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数据onClick事件传递给循环中的函数

更新时间:2021-09-06 00:08:33

在您的情况下,该问题似乎是由于关闭引起的.您应该在for循环中使用let,否则每次forLoop都会在renderRow情况下使用this.props.h.length - 1和相似性调用this.renderRow(i)

The problem in your case, seems to be caused due to closure. You should make use of let for the for loop, otherwise everytime forLoop will call this.renderRow(i) with the this.props.h.length - 1 and similary in your renderRow case as well

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (let i = 0; i < this.props.w; i++) {
    let thisButton=<FieldButton handler={this.actionFunction} key={'row'+ row +'col'+ i}></FieldButton>
    Buttons.push(thisButton)
  }
  return Buttons
}

renderField(){
  var Field = new Array(this.props.h);
  for (let i = 0; i < this.props.h; i++) {
    let row = this.renderRow(i);
    Field.push(<View key={i} style={styles.fieldWrap}>{row}</View>);
  }
  this.setState({field: Field})
}

此后,您的Parent组件已经保存了状态,您可以将其作为props传递,然后实现componentWillReceiveProps.

After this since, your Parent component already holds the state, you could pass it as props and then implement componentWillReceiveProps.

P.S.但是,如果您的子组件状态直接来自于 道具,您应该直接使用道具,而不要保留本地道具 孩子的状态

P.S. However if your child component state is directly derivable from props, you should directly use the props instead of keeping a local state in child