根据条件渲染 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

但我不能用渲染函数本身编写 javascript。有谁知道我该怎么做?感谢您提供任何帮助或建议,提前致谢。

您可以使用 if 和 return 适当的 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}

我经常为此创建一个显式函数,以避免在主 render:

中出现混乱
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/

For many React developers using JSX it is not clear how to make a dynamic JSX tag. Meaning that instead of hardcoding whether it is input or textarea or div or span (or anything else) we would like to keep it in a variable.