React loop list method: 1. map loop, the code is [let MyDom =arr.map((item,index)=>]; 2. for loop, the code is [for(var i= 0;i
React loop list method:
1.map loop
<script type="text/babel"> let arr=["吃饭","睡觉","喝水"] let MyDom =arr.map((item,index)=>{ return <p>{item}</p> }) ReactDOM.render(MyDom,document.getElementById("demoReact")) </script>
<script type="text/babel"> let arr=["吃饭","睡觉","喝水"] let MyDom =arr.map((item,index)=>{ //key值必须是独一无二的 return <p key={index}>{item}</p> }) ReactDOM.render(MyDom,document.getElementById("demoReact")) </script>
//直接回车换行 return <p key={index}>{item}</p>
//用括号包裹住换行元素 let MyDom =arr.map((item,index)=>{ return ( <p key={index}>{item}</p>) })
2.for in loop
function fun(){ let newarr=[]; for(let index in arr){ newarr.push(<p key={index}>{arr[index]}</p>) } return newarr; } ReactDOM.render(fun(),document.getElementById("demoReact"))
3.for loop
function fun(){ let newarr=[]; for(var i=0;i<arr.length;i++){ newarr.push(<p key={i}>{arr[i]}</p>) } return newarr; }
4.for each loop
function fun(){ arr.forEach(a=>{ console.log(a); }) }
Related free learning recommendations:javascript(video)
The above is the detailed content of How to loop a list in react. For more information, please follow other related articles on the PHP Chinese website!