使用ES6的map进行遍历,一定要写return
<body>
<div id="app"></div>
<!-- 注意type="text/babel" 否则无法起到babel的翻译功能 -->
<script type="text/babel">
let list = ["吃饭", "睡觉", "打豆豆"];
let dom = list.map((item, index) => {
return <p>{item}->{index}</p>
});
//渲染到根节点上
ReactDOM.render(dom, document.getElementById("app"));
</script>
</body>
最简单的 for in,效果都是一样的
<body>
<div id="app"></div>
<!-- 注意type="text/babel" 否则无法起到babel的翻译功能 -->
<script type="text/babel">
let list = ["吃饭", "睡觉", "打豆豆"];
function fun(list) {
let buffer = [];
for (let index in list) {
buffer.push(<p key={index}>{list[index]}->{index}</p>);
}
return buffer;
}
let dom = <div>{fun(list)}</div>;
//渲染到根节点上
ReactDOM.render(dom, document.getElementById("app"));
</script>
</body>
点谁谁变色
<body>
<div id="app"></div>
<!-- 注意type="text/babel" 否则无法起到babel的翻译功能 -->
<script type="text/babel">
//效果:点谁,谁就变为红色
let list = ["路飞", "鸣人", "一护"];
let nowRed = -1;
//提供虚拟dom
function fun() {
let buffer = list.map((value, index) => {
let deom =
<p style={{ color: nowRed === index ? "red" : "" }}
key={index} onClick={() => {
nowRed = index; console.log("你点了" + value); loadDom();
}}>
{value}
</p>;
return deom;
});
return buffer;
}
//渲染方法
function loadDom() {
ReactDOM.render(fun(), document.getElementById("app"));
}
//初始化时渲染一次
loadDom();
</script>
</body>