React Native:在这样的状态下使用变量字符串:this.state.variableString

时间:2016-11-02 14:36:23

标签: react-native

很难解释,但我想做这样的事情:

constructor(props) {
    super(props);

    this.state = {
        photoTree: "beautiful photo",
        photoDoor: "photo of a door",
        photoTreeSource: "/assets/tree.png",
        photoDoorSource: "/assets/door.png",
    }
}

doSomething(name) {
    let _state = "photo" + name;
    let _stateSource = _state + "Source";

    console.log(this.state. + _state);
    console.log(this.state. + _stateSource); //something like this
    console.log(this.state._state); 
}

render() {
    return(
        <View>
            <TouchableOpacity style={style.button} onPress={this.doSomething.bind(this, "Tree")} />
            <TouchableOpacity style={style.button} onPress={this.doSomething.bind(this, "Door")} />
        </View>
    )
}

我知道做一个像对象这样的对象:{树:&#34;美丽......&#34;,门:&#34; blablabla ......&#34;}&#39;会更好,但我想知道我们是否有办法像上面这样做,只是出于好奇。

2 个答案:

答案 0 :(得分:4)

如果某人有兴趣,你可以在doSomething(名字)中做类似的事情:

<my-comp [title]="'Foo\'s component'"></my-comp>

答案 1 :(得分:0)

您可以使用setState而不是创建初始化它们的新变量。