繁体   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