我计划仅在单击按钮时渲染元素或使元素可见。但无论如何都会呈现元素。即使日志说状态是假的
getInitialState: function(){
return {
number: 0,
'image1': "https://www.bignerdranch.com/img/blog/2014/07/Button-2.png",
visible1: false
}
},
add: function(){
var number = this.state.number;
number = number+1;
console.log(number);
var temp = "visible"
temp = temp + number
var s ={};
s[temp] = true;
console.log(s);
this.setState(s);
},
render: function(){
return(
<div>
<img className={"addpicture "+this.state.visible1?"visible":"invisible"} onClick={this.camera} src={this.state.image1} data-cam={1}/>
<button onClick={this.add}>Click me</button>
{console.log(this.state.visible1)}
</div>
);
}
答案 0 :(得分:3)
您的三元表达式"addpicture "+this.state.visible1?"visible":"invisible"
正在评估"addpicture " + this.state.visible
,由于字符串强制返回"addpicturefalse"
。由于所有非空字符串都是真实的,因此返回visible
。
使用parens包装三元表达式以隔离评估逻辑。
"addpicture "+ (this.state.visible1?"visible":"invisible")