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

IT技术 javascript arrays reactjs react-native
2021-05-24 05:22:35

我以这种方式在父组件中创建我的组件:

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (var i = 0; i < this.props.w; i++) {
    var 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 (var i = 0; i < this.props.h; i++) {
    var row = this.renderRow(i);
    Field.push(<View key={i} style={styles.fieldWrap}>{row}</View>);
  }
  this.setState({field: Field})
}

目标:

我必须更改 FieldButton 组件的状态。

我的问题:

更改 Childs 组件状态的正确方法是什么?

第一次尝试:

我试图将一个props绑定到父组件的状态:

 <FieldButton color={this.state.color} handler={this.actionFunction} key={'row'+ row +'col'+ i}></FieldButton>

我还实现了 componentWillReceiveProps 方法,但从未调用过。

我试图将孩子移到 for 循环之外并且它起作用了。

第二次尝试:

我尝试使用 refs:这个问题。

1个回答

您的问题似乎是由于关闭引起的。您应该使用letfor 循环,否则每次 forLoop 都会在您的 renderRow 案例中this.renderRow(i)使用 thethis.props.h.length - 1similary 调用

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.

PS 但是如果你的子组件状态可以直接从 props 派生,你应该直接使用 props 而不是在 child 中保持本地状态