【发布时间】: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])
}
问题:输出未定义。
【问题讨论】:
-
第 4 行:
thisButton应声明为 var thisButton 或 const thisButton。这可能只是一个错字。 -
没有改变任何东西。
-
你有没有像this.refField = {}这样初始化对象refField
-
我确实喜欢
this.refField = [],但也尝试过{} -
好的,那么你有没有在你的 actionFunction 中打印出你的 pos 变量以确保它是正确的?
标签: javascript arrays reactjs react-native