本文是參菜鳥教程《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 }));