在 React 中钥弯,你可以創(chuàng)建不同的組件來封裝各種你需要的行為祭刚。然后還可以根據(jù)應用的狀態(tài)變化只渲染其中的一部分译隘。
React 中的條件渲染和 JavaScript 中的一致粗恢,使用 JavaScript 操作符 if
或條件運算符來創(chuàng)建表示當前狀態(tài)的元素薇正,然后讓 React 根據(jù)它們來更新 UI片酝。
實例:
首先創(chuàng)建三個組件:
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
定義一個變量,是否登錄, isLoggedIn:
constructor(props) {
super(props);
this.state = {
isLoggedIn: true
};
再定義一個button挖腰,并設置一個事件函數(shù)雕沿,點擊button修改登錄狀態(tài):
handleClick() {
this.setState(prevState => ({
isLoggedIn: !prevState.isLoggedIn
}));
}
render() {
return (
<div>
<Greeting isLoggedIn={this.state.isLoggedIn} />
<button onClick={this.handleClick}>
{this.state.isLoggedIn ? '登出' : '登錄'}
</button>
</div>
);
}
顯示:
Code:
import React, { Component } from 'react';
import './App.css';
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: true
};
this.handleClick = this.handleClick.bind(this);
}
componentWillMount () {
console.log('this is in componentWillMount method.');
}
componentDidMount () {
console.log('this is in componentDidMount method.');
}
componentWillReceiveProps (nextProps) {
console.log('this is in componentWillReceiveProps method.');
}
// shouldComponentUpdate (nextProps,nextState) {
// console.log('this is in shouldComponentUpdate method.');
// }
componentWillUpdate (nextProps,nextState) {
console.log('this is in componentWillUpdate method.');
}
componentDidUpdate (prevProps,prevState) {
console.log('this is in componentDidUpdate method.');
}
handleClick() {
this.setState(prevState => ({
isLoggedIn: !prevState.isLoggedIn
}));
}
render() {
return (
<div>
<Greeting isLoggedIn={this.state.isLoggedIn} />
<button onClick={this.handleClick}>
{this.state.isLoggedIn ? '登出' : '登錄'}
</button>
</div>
);
}
componentWillUnmount () {
console.log('this is in componentWillUnmount method.');
}
}
export default App;
如果覺得文章寫得還行,請點個贊猴仑。如果想與我進一步交流审轮,可以關(guān)注我的公眾號或者加我的微信。
個人微信
公眾號_前端微說.jpg