每個元素都要有唯一的 key 屬性
若單純 dom 位置交換,React 不會知道,會重新渲染,故要加上 key 讓 React 得以辨識。這樣可變免重新渲染一次。
渲染陣列各項數據
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import './index.css'
const users = [
{ username: 'Jerry', age: 21, gender: 'male' },
{ username: 'Tomy', age: 22, gender: 'male' },
{ username: 'Lily', age: 19, gender: 'female' },
{ username: 'Lucy', age: 20, gender: 'female' }
]
class User extends Component {
render () {
const { user } = this.props
return (
<div>
<div>姓名:{user.username}</div>
<div>年齡:{user.age}</div>
<div>性別:{user.gender}</div>
<hr />
</div>
)
}
}
class Index extends Component {
render() {
return (
<div>
{users.map((user, i) => <User key={i} user={user} />)}
</div>
)
}
}
ReactDOM.render(
<Index onClick={() => console.log('Click')} />,
document.getElementById('root')
)