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)...
·
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 绑定的过程 */}
<button onClick={display}>{this.state.show ? '点击隐藏' : '点击显示'}</button>
{
this.state.show
?
<p>显示出来啦</p>
:
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 = <p>显示出来啦</p>
}
return <div>
{/* 这种方法省略了 this 绑定的过程 */}
<button onClick={display}>{this.state.show ? '点击隐藏' : '点击显示'}</button>
{DOM}
</div>
}
关于 v-show 就没什么好说的了吧?手动设置标签的 style 就行,很简单。
更多推荐
已为社区贡献27条内容
所有评论(0)