【问题标题】:Conditional rendering of HTML elements in React?在 React 中条件渲染 HTML 元素?
【发布时间】:2016-11-07 16:52:37
【问题描述】:

我希望有条件地呈现我的组件的一些 HTML 元素。

我有一个状态变量 Boolean,它可以是 true(想要呈现文本)或 false(想要什么都不呈现)。

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

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

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

但在这两种情况下,h1 元素都会被渲染,而不管布尔值的状态如何!

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

【问题讨论】:

  • 不,那绝对可以。您可以发布您的示例或提供更多代码吗?
  • 我可以确认三元表达式有效。你能检查一下你的布尔值的类型和值吗?

标签: javascript html reactjs


【解决方案1】:

我通常这样做:

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

如果它不起作用,请提供更多上下文,也许是一些错误消息或其他什么?

【讨论】:

  • 更短、更简单的版本很棒。
【解决方案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>

    )
  }
}

【讨论】:

    【解决方案3】:

    这样的东西行不通?

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

    }

    【讨论】:

      【解决方案4】:

      我通常会做类似以下的事情(h/t to 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>
              );
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-01
        • 2022-01-11
        • 2021-08-03
        • 2022-01-25
        • 2018-01-15
        • 2020-03-01
        • 2020-11-13
        • 2022-12-10
        • 1970-01-01
        相关资源
        最近更新 更多