查看: 15|回覆: 0

React 使用 if else 判断语句

[複製鏈接]

0

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2012-2-25
發表於 2019-8-2 10:34:00 | 顯示全部樓層 |閲讀模式

今天在写 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>
        );
    }
}





来源:https://www.cnblogs.com/dtdxrk/p/11287112.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部