2016-11-02 94 views
1

很難解釋,但我想要做這樣的事情:陣營本機:在這樣的狀態下使用的變量字符串:this.state.variableString

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

我知道,做像「照片的對象: {樹:「美麗......」,門:「blablabla ...」}'會更好,但我想知道我們是否有辦法像上面這樣做,只是出於好奇。

回答

2

如果有人感興趣,你可以做DoSomething的(名字)這樣的事情:

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

    console.log(this.state[_state]) // it work ! 
} 
0

可以使用的setState而不是創建新的變量初始化它們。

+0

我不希望創建一個新的變量我只是想顯示state.photoTree或state.photoDoor其中photoDoor是像一個字符串: 常量propertiesName =「photoDoor」 並使用它像 控制檯。日誌(this.state.propertiesName) 但我找到了一個解決方案(this.state [propertiesName]) –