React中HTML元素的条件渲染?

9

我希望有条件地渲染组件中的一些HTML元素。

我有一个布尔类型的状态变量,它可以是true(想要渲染文本)或false(不想渲染任何内容)。

在render函数的返回参数中,我尝试了以下方法:

{this.state.boolean ? <div><h1>True</h1></div> : <div></div>}

{this.state.boolean && <div><h1>True</h1></div> || <div></div>}

但是在这两种情况下,无论Boolean的状态如何,h1元素都会被渲染!

有什么想法吗?提前感谢。


4
没问题,那肯定可以。你能否提供你的例子或者更多的代码呢? - azium
我可以确认三元表达式是有效的。您能否检查一下布尔类型和值? - Akshat Mahajan
4个回答

5

我的日常工作通常包括:

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,并且这个HTML有很多条件或者本质上就很复杂。注意:返回null将不会渲染任何内容。

或者更短、更简单的版本:

{this.state.boolean && <div><h1>True</h1></div>}

如果不起作用,请提供更多上下文,例如错误消息或其他信息?

更短、更简单的版本非常棒。 - Noumenon

2

这肯定有效,听起来就像是你一直在做的事情。

查看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>

    )
  }
}

1
像这样的东西不起作用吗?
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>

    )
}

}


0
通常我做的事情类似以下方式(感谢 Chad 的代码,我借鉴并修改了它)。
class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            boolean: false
        };
    }
    render(){
        var bool = null;
        if (this.state.boolean) {
            bool = (<div><h1>True</h1></div>);
        }
        return(
            <div>
                {bool}
            </div>
        );
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接