带有引用的组件数组 [英] Array of Components with refs
问题描述
对于我的四个连续游戏,我创建了一个组件数组。我需要从父组件中调用一个特定组件的方法。
For my four in a row game I create an Array of components. I need to call a method of one specific component from the parent component.
以下是构建Field的两种方法。在renderRow中,我将ref放入构造函数中定义的Array中。
Here are the two methods that are building the Field. At renderRow I put the ref into an Array which is defined in the constructor.
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应该只打印当前引用。
The actionFunction should simply print the current ref.
actionFunction(pos) {
console.log(this.refField['row'+ pos.row +'col'+ pos.col])
}
问题:输出未定义。
编辑:
如果我console.log reField变量,则输出为:
If I console.log the reField variable this is the output:
推荐答案
解决方案是我不得不使用 let
而不是 var
来初始化for循环中的变量。
工作代码:
The solution is that I had to use let
instead of var
to initialise the variables in the for loop.
Working code:
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;
}
这篇关于带有引用的组件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!