根据react-native中传递的参数设置动态名称

Set dynamic state name based on the delivered parameter in react-native

我是 react-native 开发的新手。现在我正在尝试为 Dart 游戏编写一个简单的记分牌 "Cricket" 来尝试一下。

这基本上是一个游戏,您需要击中 15-20 和靶心区域 3 次才能关闭它们。如果你击中它们超过 3 次,你可以获得积分。

我的应用程序的第一个版本可以运行,但它很丑并且使用了很多行代码。我为每个点场(15-20 + 靶心)创建了一个函数来添加点。喜欢:

tap20(){

this.state.indicator = "x";

if(this.state.tapped_20 > 1){
    this.state.indicator = "xx";
if(this.state.tapped_20 > 2){
  this.state.indicator = "xxx";
  if(this.state.tapped_20 > 3){
  this.state.points = 20 + this.state.points

  }
}
}

this.setState({

points: this.state.points,
tapped_20: this.state.tapped_20+1,
})
}

tap19(){

this.state.indicator_19 = "x";

if(this.state.tapped_19 > 1){
    this.state.indicator_19 = "xx";
if(this.state.tapped_19 > 2){
  this.state.indicator_19 = "xxx";
  if(this.state.tapped_19 > 3){
  console.log("Ab hier Punkte..")
  this.state.points = 19 + this.state.points

  }
}
}

this.setState({

points: this.state.points,
tapped_19: this.state.tapped_19+1,
})
}

等等。我现在的方法是给函数一个参数。所以我只有一个函数可以根据给定的参数添加点。像这样:

<TouchableHighlight style={styles.button}
onPress={this.testfunc.bind(this, 20)}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}> 20 Test</Text>
 </TouchableHighlight>

其中调用函数:

testfunc(i) {

  window['this.state.indicator_' + i ] = 'test'

  console.log(this.state.indicator_20)
...

当我在浏览器中调试它时,它指出 console.log(this.state.indicator_20) 未定义。

它似乎不适用于this.state...有人知道如何解决这样的问题吗?

首先,您永远不必在 React Native 中引用 window。认为这是一个危险信号。

其次,您不能以这种方式计算对象的属性:window['this.state.indicator_' + i ]。您在一个名为 "bar" 的对象上引用了一个名为 "foo" 的 属性:bar['foo'] 并且您不能引用任何更深层次的内容(即没有 bar['foo.baz'])。

无论如何,react 为此提供了setState

testfunc(i) {
  const update = {};

  update['indicator_' + i] = 'test';

  this.setState(update);
}

然后在渲染中参考 this.state.indicator_X,它将按预期更新。

解决方案是:this.state['tapped_' + i]this.state['tapped_${i}']