实际开发中,常常需要根据用户需求动态渲染一些组件
以做一个TooList(待办清单)为例
比较窒息不优雅的方法
const List = (
listContent ?
(listContent.map((item, index) => (
<div className="each-list" key={`each-${index}`}>
<li key={`list-${index}`} onClick={() => this.ChangeState(index)} className={`list-${index}`} style={style[index]}>{item}</li>
<button className="each-button" key={`eachbutton-${index}`} onClick={() => this.onDelete(index)}>Delete</button>
</div>
))
)
: null
)
当你们看到style={style[index]}时,应该就猜到我的思路了。。创建一个listconent数组,获取数组长度,再遍历,设置每个list样式的初始值,如果哪个改变了,再根据index的索引更改。
比较高级的方法
redux 的官方示例中
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
)
style={{
textDecoration: completed ? ‘line-through’ : ‘none’
}}
嗯…维护一个是否完成的状态即可…虽然redux的使用有点麻烦,尤其对于这种程度的demo,完全大材小用?