條件渲染很多時候都是在state里面設(shè)置變量,一般為布爾值,然后由這個布爾值來控制頁面的隱藏與顯示。常見的應(yīng)用場景:
- 對視圖的條件進(jìn)行切換
- 做缺省值
Case1
父元素控制子元素的顯示,通過改變className來進(jìn)行改變,需要注意在className中添加多個類名的方法
import React from 'react';
//父元素控制子元素的顯示
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
isActive: true
}
}
changeShow = () => {
this.setState({
isActive: !this.state.isActive
})
}
render() {
return (
<div>
<button onClick={this.changeShow}>控制子元素顯示</button>
<Child isActive={this.state.isActive} />
</div>
)
}
}
class Child extends React.Component {
render() {
let strClass = null;
if (this.props.isActive) {
// 在這邊設(shè)置空格
strClass = ' active'
} else {
strClass = ""
}
return (
<div className={"content" + strClass}>
<h1>我是子元素</h1>
</div>
)
}
}
Case2
import React from "react";
export default class IfDemo extends React.Component {
/**
* 常見的應(yīng)用場景:
* 1.對視圖的條件進(jìn)行切換
* 2.做缺省值
*/
constructor(props) {
super(props);
this.state = {
isLogin: false,
names: ["ime"],
};
}
clickHandle = () => {
this.setState({
isLogin: true,
});
};
render() {
const { names } = this.state;
let showView = this.state.isLogin ? <div>iwen</div> : <div>請登陸</div>;
return (
<div>
條件渲染{showView}
<button onClick={this.clickHandle}>登錄</button>
{names.length > 0 ? (
<div>
{names.map((element, index) => {
return <p key={index}>{element}</p>;
})}
</div>
) : (
<div>等待數(shù)據(jù)</div>
)}
</div>
);
}
}
Case3
import React, { Component } from 'react'
//函數(shù)組件
function UserGreet(props) {
return <h1>歡迎登陸</h1>
}
function UserLogin(props) {
return <h1>請先登陸</h1>
}
export default class App5 extends Component {
constructor(props) {
super(props)
this.state = {
isLogin: false
}
}
render() {
let element = null
if (this.state.isLogin) {
element = <UserGreet />
} else {
element = <UserLogin />
}
return (
<div>
<h1>這是頭部</h1>
{element}
<h1>這是三元運算符</h1>
{this.state.isLogin ? <UserGreet /> : <UserLogin />}
<h1>這是尾部</h1>
</div>
)
}
}
3種不同方式渲染組件
import React, { Component } from 'react'
function UserGreeting(props) {
return (
<p>歡迎{props.username}</p>
)
}
function GuestGreeting(props) {
return (
<p>請登陸!</p>
)
}
export default class Greeting extends Component {
constructor(props) {
super(props)
this.state = {
isLogin: true
}
}
render() {
let greeting = <GuestGreeting />
if (this.state.isLogin) {
greeting = <UserGreeting username="ha" />
}
return (
<div>
<h3>1.最基本的通過if實現(xiàn)的條件渲染</h3>
{greeting}
<h3>2.通過三元運算符實現(xiàn)條件渲染</h3>
{this.state.isLogin ? <UserGreeting username="la" /> : <GuestGreeting />}
<h3>3.通過&&實現(xiàn)條件渲染</h3>
{
this.state.isLogin && <UserGreeting username="he" />
}
{
this.state.isLogin || <GuestGreeting />
}
</div>
)
}
}