将数据onClick事件传递给循环中的函数 [英] Pass data onClick event to the function in loop

查看:91
本文介绍了将数据onClick事件传递给循环中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过以下方式在父组件中创建我的组件:

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

目标:

我必须更改FieldButton组件的状态.

I have to change the state of the FieldButton component.

我的问题:

更改Childs组件状态的正确方法是什么?

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

首次尝试:

我试图将prop绑定到父组件的状态:

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>

我还实现了componentWillReceiveProps方法,但从未调用过.

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

我试图将孩子移到for循环之外,并且奏效了.

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

第二次尝试:

我尝试使用裁判:这个问题.

推荐答案

在您的情况下,该问题似乎是由于关闭引起的.您应该在for循环中使用let,否则每次forLoop都会在renderRow情况下使用this.props.h.length - 1和相似性调用this.renderRow(i)

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

此后,您的Parent组件已经保存了状态,您可以将其作为props传递,然后实现componentWillReceiveProps.

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

P.S.但是,如果您的子组件状态直接来自于 道具,您应该直接使用道具,而不要保留本地道具 孩子的状态

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

这篇关于将数据onClick事件传递给循环中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆