React(8)条件渲染(类似 Vue 的 v-if)

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 <div>
            {/* 这种方法省略了 this 绑定的过程 */}
            
            {
                this.state.show
                    ?
                    

显示出来啦

: null } div> } 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 = 

显示出来啦

} return
{/* 这种方法省略了 this 绑定的过程 */} {DOM}
}

关于 v-show 就没什么好说的了吧?手动设置标签的 style 就行,很简单。

你可能感兴趣的:(React教程,React,教程)