0

I create my component in the parent component this way:

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (var i = 0; i < this.props.w; i++) {
    var thisButton=<FieldButton 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.setState({field: Field})
}

The Goal:

I have to change the state of the FieldButton component.

My question:

What is the right way to change the Childs component state?

First Attempt:

I tried to bind a prop to the state of the parent component:

 <FieldButton color={this.state.color} handler={this.actionFunction} key={'row'+ row +'col'+ i}></FieldButton>

I also implemented the componentWillReceiveProps Method but it was never called.

I tried to move the child outside of the for loop and it worked.

Second Attempt:

I tried to use refs: this question.

1 Answer 1

0

The problem in your case, seems to be caused due to closure. You should make use of let for the for loop, otherwise everytime forLoop will call this.renderRow(i) with the this.props.h.length - 1 and similary in your renderRow case as well

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (let i = 0; i < this.props.w; i++) {
    let thisButton=<FieldButton 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.setState({field: Field})
}

After this since, your Parent component already holds the state, you could pass it as props and then implement componentWillReceiveProps.

P.S. However if your child component state is directly derivable from props, you should directly use the props instead of keeping a local state in child

Sign up to request clarification or add additional context in comments.

2 Comments

if you want you can answer the linked question. Your answer would fit there very well.
Glad the answer helped you. Its, fine that you could yourself add an answer to the linked question or maybe delete it. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.