一、条件渲染(类组件写法)
1、在react里做条件渲染,像vue中的v-if、v-else、v-show
2、单一元素的条件渲染
语法:{ bol && <jsx元素 /> }
如果布尔值等于真,后面的jsx元素就渲染,如果布尔值等于假则不渲染
例子:
javascript
import { Component } from 'react';
class A extends Component {
constructor (props) {
super(props);
this.state = {
bol1: true,
};
}
render () {
const { bol1 } = this.state;
return (
<div>
<h1>类组件</h1>
<hr />
{ bol1 && <h1>你好</h1> }
<button onClick={() => this.setState(state => ({ bol1: !state.bol1 }))}>显示/隐藏</button>
</div>
);
}
}
export default A;
state可以用_下划线代替
() => this.setState(_ => ({ bol1: !_.bol1 }))
3、两个元素的条件渲染
语法:{ bol ? <jsx元素1 /> : <jsx元素2 /> }
例子:
javascript
import { Component } from 'react';
class A extends Component {
constructor (props) {
super(props);
this.state = {
bol2: true,
};
}
render () {
const { bol2 } = this.state;
return (
<div>
<h1>类组件</h1>
<hr />
{ bol2 ? <h1>北京</h1> : <h1>上海</h1> }
<button onClick={() => this.setState(state => ({ bol2: !state.bol2 }))}>切换</button>
</div>
);
}
}
export default A;
4、多个元素的条件渲染,建议封装自定义渲染函数
比如:function renderSomething(...arg) { }
传一些自定义参数,在里面可以做任何想做的事情,最后返回一个满足条件的视图结构
例子:
javascript
import { Component } from 'react';
class A extends Component {
constructor (props) {
super(props);
this.state = {
num: 0,
};
}
renderRow () {
const { num } = this.state;
// do something
let result = null;
if (num === 0) {
result = <h1>北京</h1>;
} else if (num === 1) {
result = <h1>上海</h1>;
} else if (num === 2) {
result = <h1>广州</h1>;
}
return result;
}
render () {
//const { bol1 } = this.state;
return (
<div>
<h1>类组件</h1>
<hr />
{ this.renderRow() }
<button onClick={() => this.setState(state => ({ num: (state.num + 1)%3 }))}>切换</button>
</div>
);
}
}
export default A;
5、实现v-show
使用display:none来实现元素的显示与隐藏
语法:<style={{display:(bol ? '显示' : '隐藏')}} jsx />
style里第一对是jsx的尖括号,第二对是键值对
例子:
javascript
import { Component } from 'react';
class A extends Component {
constructor (props) {
super(props);
this.state = {
bol3: true,
};
}
render () {
const { bol3 } = this.state;
return (
<div>
<h1>类组件</h1>
<hr />
<h1 style={{display:(bol3 ? 'block' : 'none')}}>广州</h1>
<button onClick={() => this.setState(state => ({ bol3: !state.bol3 }))}>显示/隐藏</button>
</div>
);
}
}
export default A;
二、条件渲染(函数式组件写法)
1、例子
javascript
import { useState } from 'react';
function A () {
const [idx, setIdx] = useState(0);
// 使用箭头函数封装
const renderLine = () => {
let result = null;
switch(idx) {
case 0:
result = <h1>北京</h1>;
break;
case 1:
result = <h1>上海</h1>;
break;
case 2:
result = <h1>广州</h1>;
break;
default:
result = null;
break;
}
return result;
};
return (
<div>
<h1>函数式组件</h1>
{ renderLine() }
<button onClick={() => setIdx((idx + 1)%4)}>切换</button>
</div>
);
}
export default A;