React条件渲染
React条件渲染和JavaScript的条件运算,如if…else、三元运算符差不多
- 直接通过条件运算返回要渲染的JSX对象
- 通过条件运算得出JSX对象,再将JSX对象渲染到模板中
function UserGreet(props){
return (<h1>登录</h1>)
}
function UserLogin(props){
return (<h1>请先登录</h1>)
}
class Login extends React.Component {
constructor(props) {
super(props)
this.state = {
isLogin: true
}
}
render() {
let element = null
if (this.state.isLogin) {
element = (<UserGreet />)
} else {
element = (<UserLogin />)
}
return (
<div>
{element}
<h2>三元运算符</h2>
{this.state.isLogin?<UserGreet />:<UserLogin />}
</div>
)
}
}
列表渲染
- 将列表内容拼装成数组放置到模板中,将数据拼装成数组的JSX对象(不推荐)
- 使用数组的map方法,对每项数据按照JSX的形式进行加工,最终得到每一项都是JSX对象的数组,再将数组渲染到模板中
注意:Key值需要放置到每一项中,不建议使用索引作为 key,因为这样可能会导致性能问题,甚至会引起组件状态的问题。在默认的情况下,即我们没有显式指定 key 时,React 将使用索引作为列表项目的 key