带引用的组件数组

时间:2017-12-09 23:40:45

标签: javascript arrays reactjs react-native

对于我的四连胜游戏,我创建了一个组件数组。我需要从父组件调用一个特定组件的方法。

以下是构建Field的两种方法。在renderRow中,我将ref放入一个在构造函数中定义的Array中。

renderRow(row){
  var Buttons = new Array(this.props.w)
    for (var i = 0; i < this.props.w; i++) {
    thisButton=<FieldButton ref={(r) => { this.refField['row'+ row +'col'+ i] = r; }} 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.field = Field;
}

actionFunction应该只打印当前的参考。

actionFunction(pos) {
  console.log(this.refField['row'+ pos.row +'col'+ pos.col])
}

问题:输出未定义。

修改 如果我在console.log中使用reField变量,那么这是输出: enter image description here

2 个答案:

答案 0 :(得分:0)

React实际上只有一个名为refs的特殊属性!

https://reactjs.org/docs/refs-and-the-dom.html

实际上,您只需为对象的引用设置名称,然后使用this.refs.referenceName访问该类中任何位置的对象。请注意,当您在对象上设置引用时,属性名称为&#39; ref&#39; (单数)当你想要访问它时,你使用&#39; this.refs&#39; (复数)。 例如:

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

现在,如果您需要从actionFunction获取FieldButton:

actionFunction(pos) {
  console.log(this.refs['row'+ pos.row +'col'+ pos.col])
}

注意:还要确保您的函数绑定到类实例。

答案 1 :(得分:0)

解决方案是我必须使用let而不是var来初始化for循环中的变量。 工作代码:

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (let i = 0; i < this.props.w; i++) {
    let thisButton=<FieldButton ref={(r) => { this.refField['row'+ row +'col'+ i] = r; }} 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.field = Field;
}