React——条件渲染

本文介绍了React中基于状态的条件渲染技巧,包括使用变量存储不同状态下的元素以实现动态渲染,以及如何通过返回null来阻止组件渲染,同时展示了如何管理组件可见性的示例。

在React中,你可以创建各种不同的组件,然后根据应用的状态渲染出它们其中的一般部分。

一.用变量存储元素

可以将元素保存到一个变量中,通过为变量赋不同的值去渲染不同的元素

function LoginButton(props){
    return <button onClick={props.handleClick}>Login</button>
}
function LogoutButton(props){
    return <button onClick={props.handleClick}>Logout</button>
}
class LoginCtr extend React.Component{
    constructor(props){
        super(props);
        this.state={isLogin:false}
    }
    logOut(){
        this.setSate({
            isLogin:false
        })
    }
    logIn(){
        this.setState({
            isLogin:true
        });
    }
    render(){
        let button;
        if(this.state.isLogin){
            button = <LogoutButton handleClick={this.logOut.bind(this)}/>
        } else {
            button = <LogInButton handleClick={this.logIn.bind(this)}/>
        }
        return (<div>{button}</div>);
    }
};

 二.阻止组件渲染

在少数情况下,你可能想让组件隐藏它自己而非被渲染到其他组件中,可以通过return null达到这种效果

 

function Waring(props){
    if(!props.waring){
       return null;
    }
    return <div>this is a waring</div>
}
class waringCtr extend React.Component{
    constructor(props){
        super(props);
        this.state = {hasWarn:false}
    }
    handle(){
        let hasWarn = this.state.hasWarn;
        hasWarn = !hasWarn;
        this.setState({
            hasWarn:hasWarn
        });
    }
    render(){
        return (
            <div>
                <button onClick={this.handle.bind(this)}>{this.state.hasWarn ? 'hideWarn':'showWarn'}</button>
                <Waring waring={this.state.hasWarn}/>
            </div>
        )
    }
};

 

 在组件的render方法中返回null,并不会影响组件生命周期函数的调用,所以Waring组件的componentWillUpdate方法和componentDidUpdate方法还是会
被调用

 

转载于:https://www.cnblogs.com/QxQstar/p/7531356.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值