【问题标题】:Array of Components with refs带有 refs 的组件数组
【发布时间】:2017-12-09 23:40:45
【问题描述】:

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

这是构建字段的两种方法。在 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 变量,这是输出:

【问题讨论】:

  • 第 4 行:thisButton 应声明为 var thisButton 或 const thisButton。这可能只是一个错字。
  • 没有改变任何东西。
  • 你有没有像this.refField = {}这样初始化对象refField
  • 我确实喜欢this.refField = [],但也尝试过{}
  • 好的,那么你有没有在你的 actionFunction 中打印出你的 pos 变量以确保它是正确的?

标签: javascript arrays reactjs react-native


【解决方案1】:

React 实际上有一个特殊的属性,叫做 refs!

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

实际上,您可以为对象的引用设置一个名称,然后使用 this.refs.referenceName 在类中的任何位置访问该对象。请注意,当您在对象上设置引用时,属性名称是“ref”(单数),而当您要访问它时,请使用“this.refs”(复数)。 例如:

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])
}

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

【讨论】:

  • 我之前确实尝试过,我得到了这个:Element ref was specified as a string (add) but no owner was set. You may have multiple copies of React loaded. 所以我决定使用另一种方式。
  • 那么你的问题是你正在加载多个 React 副本。一旦你解决了这个问题,你就可以解决这个问题。可能是您的依赖项之一正在加载 React 的副本?不过,您需要解决这个问题,因为一切都可以正常工作,只是反应的一个副本具有正确的数据,而另一个副本(副本)没有,这就是调用 actionFunction 的地方。谁知道如果你有多个 React 副本会发生什么,它可能会导致很多像这样的神秘错误。
【解决方案2】:

解决方案是我必须使用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;
}

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2021-05-26
    • 2019-12-14
    • 2018-10-02
    • 2020-10-23
    • 2017-06-12
    相关资源
    最近更新 更多