zoukankan      html  css  js  c++  java
  • React 使用 if else 判断语句

    今天在写 React 时,在 render 的return中既然不能使用if判断语句,所以就整理一些在react中使用if 的方式,可根据自己的实际情况选择:

    方式一:
    class LLL extends React.Component {
        constructor(props){
            super(props);
            this.judge = false
        }
        render(){
            let Message 
            if (this.judge) {
                Message = (
                    <span>
                       <h5>It`s my life!</h5>
                    </span>
                )
            } else {
                Message = (
                    <h5>I think that's more than just like it!</h5>
                )
            }
            return(
                <div>
                    <h4>Wellcom LLL</h4>
                    {Message}
                </div>
            );
        }
    }
    
    方式二:
    class LLL extends React.Component {
        constructor(props){
            super(props);
            this.judge = false
        }
    
        Message(){
            if (this.judge) {
                return (
                    <span>
                       <h5>It`s my life!</h5>
                    </span>
                )
            } else {
                return (
                    <h5>I think that's more than just like it!</h5>
                )
            }
        }
        render(){
            return(
                //1
                <div>
                    <h4>Wellcom LLL</h4>
                    {this.Message()}
                </div>
            );
        }
    }
    
    方式三:三元运算符
    class LLL extends React.Component {
        constructor(props){
            super(props);
            this.judge = false
        }
        
        render(){
            return(
                //1
                <div>
                    <h4>Wellcom LLL</h4>
                    {this.judge ? "It`s my life!" : "I think that's more than just like it!"}
                </div>
            );
        }
    }
    
    方式四:
    class LLL extends React.Component {
        constructor(props){
            super(props);
            this.judge = false
        }
    
        render(){
            return(
                //1
                <div>
                    <h4>Wellcom LLL</h4>
                    {
                        this.judge 
                        ? 
                        <span>
                            <h5>It`s my life!</h5>
                        </span>
                        :
                        <h5>I think that's more than just like it!</h5>
                    }
                </div>
            );
        }
    }
    



  • 相关阅读:
    A1049. 命题逻辑
    矩形面积交:输出0.00
    完美的代价
    枚举孪生素数对
    改变参数的两种方法
    二面准备:React、Typescript、其他基础补充
    【TypeScript】基础及问题汇总
    【React】做一个百万答题小项目
    【React】相关题目总结
    【React】半小时深刻理解《半小时深刻理解React》(老套娃了)
  • 原文地址:https://www.cnblogs.com/dtdxrk/p/11287112.html
Copyright © 2011-2022 走看看