我希望有条件地呈现我的组件的一些HTML元素。
我有一个状态变量Boolean,它可以是true (希望呈现文本)或false (希望呈现任何内容)。
在render函数的返回参数中,我尝试了以下方法:
{this.state.boolean ? <div><h1>True</h1></div> : <div></div>}
{this.state.boolean && <div><h1>True</h1></div> || <div></div>}但在这两种情况下,无论布尔值的状态如何,都会呈现h1元素!
有什么想法吗?提前谢谢。
发布于 2016-11-08 06:06:36
我通常这样做:
outputHTML(boolean) {
if(!boolean) return null;
return (
<div>
Something you wanted to show if the boolean was present
</div>
)
}
render() {
return (
<div>
{this.outputHTML(this.state.boolean)}
</div>
)
}如果你想要有条件地呈现的HTML有很多条件或者本质上是复杂的。注意:返回null将不会渲染任何内容。
或者更短、更简单的版本:
{this.state.boolean && <div><h1>True</h1></div>}如果它不工作,请提供更多的上下文,也许一些错误消息或其他什么?
发布于 2016-11-08 03:49:47
这绝对是有效的,听起来像你一直在做的事情。
检查bin
https://jsbin.com/qomofonera/edit?html,js,output
class Demo extends React.Component{
constructor(props){
super(props);
this.state = {
boolean: false
};
}
render(){
return(
<div>
{this.state.boolean ? <div><h1>True</h1></div> : <div><h1>False</h1></div>}
</div>
)
}
}发布于 2016-11-08 02:50:25
像这样的东西不起作用?
class Demo extends React.Component{
constructor(props){
super(props);
this.state = {
boolean: false
};
}
render(){
return(
<div>
{this.state.boolean && <div><h1>True</h1></div>}
</div>
)
}}
https://stackoverflow.com/questions/40470386
复制相似问题