上一篇介绍了react的state和绑定事件,这一篇会谈一谈react的列表渲染以及条件渲染。
react实质上并没有提供相关列表渲染和条件渲染的封装,也就意味着不能像vue中使用一个指令来完成
在react里达到这些效果,需要使用一些数组的方法
列表渲染
在react里实现列表渲染,需要用到数组的map方法
map()
map方法用于分别处理数组中的成员,返回新的数组
let nameList = ['tom','jack','bob']
// 第一个参数是数组的成员值,第二个参数是成员的索引值
let newList = nameList.map((item,i)=>{
console.log(item,i)
return `第${i+1}个名字是${item}`
})
console.log(newList)
// ['第1个名字是tom','第2个名字是jack','第3个名字是bob']
使用map方法实现列表渲染
实现列表渲染,需要用map方法遍历数组,然后返回一个jsx对象即可
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
list: ["tom", "jack", "bob"],
};
}
logName(name){
console.log(name)
}
render() {
return (
<div>
{this.state.list.map((item, index) => (
{/* 要指定一个key */}
<p key={index} onClick={()=>{this.logName(item)}}>{`第${index + 1}个名字:${item}`}</p>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
条件渲染
在react中实现条件渲染,实际上就是根据不同的条件返回不同的jsx对象,主要有2种方法来实现
根据不同的条件返回不同的结构或者子组件
返回不同结构的形式
function Loginstate(props){
if(props.isLogin==true){
return <h2>欢迎回来!</h2>
}else{
return <h2>请登录!</h2>
}
}
ReactDOM.render(<Loginstate isLogin={true}/>,document.getElementById('root'));
还可以用返回不同子组件的形式
function Login(props){
return <h2>欢迎回来!</h2>
}
function Logout(props){
return <h2>请登录!</h2>
}
function Loginstate2(props){
if(props.isLogin==true){
return <Login />
}else{
return <Logout />
}
}
ReactDOM.render(<Loginstate2 isLogin={false}/>,document.getElementById('root'));
和运算符 && 一起使用
利用逻辑与的短路特性,我们可以使用&&来完成条件渲染
在 JavaScript 中,true && expression 总是会返回 expression, 而 false && expression 总是会返回 false。
class Notice extends React.Component{
constructor(props){
super(props);
this.state={
username:'张二狗',
messages:[
'新邮件',
'新的待办'
]
}
}
render(){
return(
<div>
<h2>你好,{this.state.username}</h2>
{/* 如果条件为false,直接返回false,逻辑与后面的语句不执行 */}
{/* 如果条件为true,则返回后面的jsx对象生成结构 */}
{
this.state.messages.length>0 && <p>你有{this.state.messages.length}条消息</p>
}
</div>
)
}
}
ReactDOM.render(<Notice />,document.getElementById('root'));
以上就是react列表渲染和条件渲染实现方法的介绍,下一篇会聊一聊react的表单数据绑定以及react的生命周期