先學30天React再說之react基礎進階(Part9)

本文是參菜鳥教程《React 条件渲染》一文來學習和總結的。

1:點擊button互相切換 

<div id="example"></div>

<script type="text/babel">
class Allbox extends React.Component {
  constructor(props) {
    super(props);
	 this.ZhuCeBtnclick = this.ZhuCeBtnclick.bind(this);
    this.state = {bool: false};
  }
  ZhuCeBtnclick(){
  	this.setState({bool: !this.state.bool})
  }
  render() {
    const bool = this.state.bool;
	let btn;
	if(bool){
		btn = <WelcomeBtn onClick={this.ZhuCeBtnclick} />
	}else{
		btn = <ZhuCeBtn onClick={this.ZhuCeBtnclick}/>
	}
	
    return (
      <div>
        <Greeting bool={bool} />
		{btn}
      </div>
    );
  }
}

function ZhuCe(props){
	return <h2>請先註冊</h2>
}
function Welcome(props){
	return <h2>歡迎回來</h2>
}
function Greeting(props){
	const bool = props.bool;
	return(
		bool?(<Welcome/>):(<ZhuCe/>)	
	)	
}
function ZhuCeBtn(props){
	return <button type="button" onClick={props.onClick}>註冊</button>
}
function WelcomeBtn(props){
	return <button type="button" onClick={props.onClick}>歡迎</button>
}
ReactDOM.render(
  <Allbox/>,
   document.getElementById('example')
);
</script>

點擊之前:

點擊之后:

在自己手寫的過程中出現了以下問題:

1:方法名的大小寫問題

2:方法傳參問題

説明:

1:方法名要ZhuCe這樣寫,zhuce這樣寫會出錯的。

2:function 裏面傳參是props,不是this.props

3:三元運算符:bool?(<Welcome/>):(<ZhuCe/>)    要這樣寫,用括號把組件包裹起來。

4:组件的 render 方法返回 null 并不会影响该组件生命周期方法的回调。例如,componentWillUpdate 和 componentDidUpdate 依然可以被调用。

2:點擊隱藏,再點擊顯示

<style>
button {
  height: 40px;
  width: 200px;
}
.warning {
  background-color: green;
  text-align: center;
  width: 100%;
  padding: 10px;

  font-size: 14pt;
  color: white;
}
</style>
</head>
<body>
<div id="example"></div>

<script type="text/babel">
var btnstyle={
	color:'blue',
	borderRadius:'5px'
}
function Warning(props){
	if(!props.warn){
		return null
	}
	return (<p className="warning">消息</p>)
}
class Page extends React.Component {
  constructor(props) {
   		super(props);		
		this.state = {bool:true};
		this.Btnclick = this.Btnclick.bind(this);
  }

 Btnclick(){
		this.setState(prevState=>({bool:!prevState.bool}))
	}
  
 render(){
		return(
		 <div>
			<Warning warn = {this.state.bool}/>
			 <button onClick={this.Btnclick} style = {btnstyle}>
          		{this.state.bool?'隱藏':'顯示'}
				</button>
		   </div>
		)
	}
}

ReactDOM.render(
  <Page />,
  document.getElementById('example')
);
</script>

 點擊之前:

點擊之後:

 

説明:

setState() 可以接收一个函数,这个函数接受两个参数,第一个参数表示上一个状态值,第二参数表示当前的 props:

this.setState((prevState, props) => ({
    //do something here
}));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值