绑定
return (
<div>
// 绑定普通属性
<h2 title={title}>我是标题</h2>
<img src={getSizeImage(imgUrl,140)} alt="">
<a href={link} target="_balnk">百度一下</a>
// 绑定class
<div className="box title"></div>
<div className={"box title" + (active ? "active" : "")}></div>
<label htmlFor=""></label>
// 绑定style
<div style{{color: "red", fontSize: "50px"}}></div>
</div>
)
条件渲染
this.state = {
isLogin: true
}
render() {
let welcome = null
if (this.state.isLogin) {
welcome = <h2>欢迎回来</h2>
} else {
welcome = <h2>请先登录</h2>
}
return (
<div>{welcome}</div>
<button>{this.state.isLogin ? '退出' : '登录'}</button>
<h2>{ this.state.isLogin && '登录成功'}</h2>
)
}
this.state = {
isLogin: true
}
render() {
const { isLogin } = this.state
return (
<div>
<button onClick={e=> this.loginClick()}>{isLogin ? '退出' : '登录'}</button>
<h2 style="{{display: (isLogin ? 'block' : 'none')}}"></h2>
</div>
)
}
loginClick(){
this.setState({ isLogin = !this.state.isLogin})
}
列表渲染
render(){
return (
<ul>
{
this.state.number.map(item => {
return <li>{item}</li>
})
}
</ul>
<ul>
{
this.state.number.filter(item => item > 50).map(item=> <li>{item}</li>)
}
</ul>
)
}
jsx的本质
jsx仅仅只是React.createElement(component,props,...children)函数的语法糖
所有的jsx最终都会被转换成React.createElement的函数调用
React.createElement最终创建出来一个ReactElement对象
React利用ReactElement对象组成一个js对象树,也就是虚拟dom
为什么采用虚拟dom
1.很难跟踪状态发生的改变:原有的开发模式,很难跟踪到状态发生的改变,不方便针对我们应用程序的调试
2.操作真实dom的性能较低:传统开发模式会频繁操作dom,而这一做法的性能非常低,dom操作会引起浏览器的回流和重绘