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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容