查看: 3|回复: 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.

在本版发帖返回顶部