根据条件渲染JSX元素

时间:2016-10-26 09:08:17

标签: javascript reactjs components jsx

所以我在我正在处理的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。有谁知道我怎么做到这一点?如有任何帮助或建议,请提前感谢。

4 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:1)

我经常为此创建一个显式函数,以避免主渲染中的混乱:

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

答案 2 :(得分:0)

单行示例

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

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

答案 3 :(得分:-1)

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

  

对于许多使用JSX的React开发人员来说,目前尚不清楚如何制作一个   动态JSX标记。意思是代替硬编码是否存在   输入或textarea或div或span(或其他任何)我们想要的   将它保存在变量中。

相关问题