在React中镜会,可以創(chuàng)建不同的組件來封裝各種需要的行為乓土,還可以根據(jù)應(yīng)用的狀態(tài)變化只渲染其中一部分踢匣。
使用 if 或條件運(yùn)算符來創(chuàng)建表示當(dāng)前狀態(tài)的元素童社,然后讓React根據(jù)他們來更新UI求厕。
Example:
無狀態(tài)組件:
function UserGreeting(props){
return <h1>Welcome back !</h1>;
}
function GuestGreeting(props){
return <h1>Please sign up.</h1>;
}
//登錄組件
function LoginButton(props) {
return(
<button onClick={props.onClick}>Login</button>
);
}
//注銷組件
function LogoutButton(props) {
return(
<button onClick={props.onClick}>Logout</button>
);
}
創(chuàng)建一個(gè) Greeting 組件,根據(jù)用戶是否登錄來顯示其中之一:
function Greeting(props){
const isLoggedIn = props.isLoggedIn ;
if(isLoggedIn ){
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
<Greeting isLoggedIn ={false} />,
document.getElementById('root')
);
創(chuàng)建一個(gè)名為 LoginControl 的有狀態(tài)組件:
它會(huì)根據(jù)當(dāng)前的狀態(tài)來渲染<LoginButton />或<LogoutButton />, 它也將渲染前面例子中的<Greeting />.
class LoginControl extends React.Component {
constructor(props){
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state={
isLoggedIn: false
};
}
handleLoginClick(){
this.setState({isLoggedIn: true});
}
handleLogoutClick(){
this.setState({isLoggedIn: false});
}
render(){
const isLoggedIn = this.state.isLoggedIn;
let button = null;
if(isLoggedIn){
button = <LogoutButton onClick={this.handleLogoutClick} />;
}else{
button = <LoginButton onClick={this.handleLoginClick} />;
}
return(
<div>
<Greeting isLoggedIn ={isLoggedIn} />
{button}
</div>
);
}
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
阻止組件渲染
在極少數(shù)的情況下扰楼,可能希望隱藏組件呀癣,及時(shí)它被其他組件渲染。讓render方法返回null而不是它的渲染結(jié)果即可實(shí)現(xiàn)弦赖。
<WarningBanner />根據(jù)屬性warn的值條件渲染项栏,
如果warn的值是false,則組件不會(huì)渲染:
if (!props.warn) {
return null;
}
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning">
Warning!
</div>
);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true}
this.handleToggleClick = this.handleToggleClick.bind(this);
}
handleToggleClick() {
this.setState(prevState => ({
showWarning: !prevState.showWarning
}));
}
render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} />
<button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);