14 条件渲染 (类似 vue 的 v-if)
讲道理说, React 本身的条件渲染, 没有 vue.js 用起来舒服 Vue.js 只需要在标签上添加 v-if 或者 v-show 就行, 但 React 就比较麻烦了
- class HelloWord extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- show: false
- }
- }
- // 渲染函数, this 指向实例本身
- render() {
- let display = this.display.bind(this) return < p > {
- /* 这种方法省略了 this 绑定的过程 */
- } < button onClick = {
- display
- } > {
- this.state.show ? '点击隐藏': '点击显示'
- } < /button>
- {
- this.state.show
- ?/
<p > 显示出来啦 </p > :null
- } < /p>
- }
- display() {
- this.setState({
- show: !this.state.show
- })
- }
- }/
如以上示例, 通过三元操作符里面, 返回 JSX 语法的 DOM 标签, 或者 null , 来决定是否显示;
也可以将 JSX 语法的 DOM 作为变量, 像下面这样使用
- render() {
- let display = this.display.bind(this) let DOM = null
- if (this.state.show) {
DOM = <p > 显示出来啦 < /p>
- }
- return < p >
{/ * 这种方法省略了 this 绑定的过程 * /}
- <button onClick={display}>{this.state.show ? '点击隐藏' : '点击显示'}</button > {
- DOM
- } < /p>
- }/
关于 v-show 就没什么好说的了吧? 手动设置标签的 style 就行, 很简单
来源: https://www.2cto.com/kf/201802/721121.html