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 ...」}'會更好,但我想知道我們是否有辦法像上面這樣做,只是出於好奇。
我不希望創建一個新的變量我只是想顯示state.photoTree或state.photoDoor其中photoDoor是像一個字符串: 常量propertiesName =「photoDoor」 並使用它像 控制檯。日誌(this.state.propertiesName) 但我找到了一個解決方案(this.state [propertiesName]) –