Skip to content Skip to sidebar Skip to footer

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. Here are the two methods that are building t

Solution 1:

React actually has a special property just for this called refs!

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

You can actually just set a name for the reference to the object and then access that object anywhere in your class using this.refs.referenceName. Do note that when you set the reference on the object the property name is 'ref' (singular) and when you want to access it you use 'this.refs' (plural). For instance:

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
}

Now, if you need to get that FieldButton from your actionFunction:

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

Note: also make sure your function is being bound to the class instance.


Solution 2:

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;
}

Post a Comment for "Array Of Components With Refs"