簡體   English   中英

根據條件渲染JSX元素

[英]Render JSX element based on condition

所以我在一直在研究的Web應用程序中有一個簡單的組件,我想知道是否有一種方法可以基於this.props.item的值在此組件中呈現元素。

這是我的JSX:

var React = require("react"); var actions = require("../actions/SchoolActions");

module.exports = React.createClass({
    deleteSchool: function(e){
        e.preventDefault();
        actions.deleteSchool(this.props.info);
    },
    render:function(){
        return(
            <div className="panel panel-default">
                <div className="panel-heading">
                    {this.props.info.name}
                    <span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span>
                </div>
                <div className="panel-body">{this.props.info.tagline}</div>
            </div>
        )
    } })

我希望能夠做這樣的事情:

   render:function(){
        return(
  code blah blah...

if (this.props.info = "nothing"){
    <div className="panel-body">{this.props.info.tagline}</div>
     }

  ...code blah blah

但是我不能用render函數本身編寫javascript。 有人知道我該怎么做嗎? 任何幫助或建議,不勝感激,在此先感謝您。

您可以使用if使用條件渲染if並返回適當的jsx

render(){
    if(something){
       return(<MyJsx1/>)
    }else{
       return(<MyJsx2/>)
    }
}

您可以為您的組件加價:

       render:function(){
            return(
                <div className="panel panel-default">
                    <div className="panel-heading">
                        {this.props.info.name}
                        <span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span>
                    </div>
                   {this.props.info = "nothing"?
                   (<div className="panel-body">{this.props.info.tagline}</div>)
                   :null}

                </div>
            )
        } })

https://facebook.github.io/react/docs/conditional-rendering.html

單行示例

{(this.state.hello) ? <div>Hello</div> : <div>Goodbye</div>}

要么

{(this.state.hello) ? <div>Hello</div> : false}

我經常為此創建一個顯式函數,以避免主渲染中出現混亂:

var ChildComponent = React.createClass({
  render: function () {
      return (<p>I am the child component</p>)
  }
});

var RootComponent = React.createClass({

  renderChild: function () {
    if (this.props.showChild === 'true') {
      return (<ChildComponent />);  
    }

    return null;
  },

  render: function () {
   return(
      <div>
        { this.renderChild() }
        <p>Hello World!</p>
      </div>
     )
  }
});

http://reactkungfu.com/2016/11/dynamic-jsx-tags/

對於許多使用JSX的React開發人員來說,不清楚如何制作動態JSX標簽。 意思是不是要對輸入,文本區域,div或span(或其他任何東西)進行硬編碼,我們希望將其保留在變量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM