function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); return ( <ul>{listItems}</ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );
keys用于给数组中元素一个稳定的标识。选取key得最好方法是选择能够唯一标识这个item的字符串。如果没有独特的标识,在万不得已的情况下可以选择item的index作为key值。
const todoItems = todos.map((todo, index) => // Only do this if items have no stable IDs <li key={index}> {todo.text} </li> );
key值只有在数组中才有意义。务必
把 key
添加到子级数组里组件本身上,而不是每个子级内部最外层 HTML 上:
For example, if you extract a ListItem
component, you should keep the key on the<ListItem />
elements in the array rather than on the root <li>
element in the ListItem
itself.
// incorrect key usage function ListItem(props) { const value = props.value; return ( // Wrong! There is no need to specify the key here: <li key={value.toString()}> {value} </li> ); } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Wrong! The key should have been specified here: <ListItem value={number} /> ); return ( <ul> {listItems} </ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );
// correct function ListItem(props) { // Correct! There is no need to specify the key here: return <li>{props.value}</li>; } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Correct! Key should be specified inside the array. <ListItem key={number.toString()} value={number} /> ); return ( <ul> {listItems} </ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );
一般的做法是,将key用在map()函数中。key值不会传递给组件,如果你的组件需要同样的值,明确的将其定义为prop,并且使用其他的名字
const content = posts.map((post) => <Post key={post.id} id={post.id} title={post.title} /> );
注意:数字型属性会按大小排序并且排在其它属性前面。一旦发生这种情况,React 渲染组件的顺序就是混乱。可能在 key 前面加一个字符串前缀来避免:
render() { var items = {}; this.props.results.forEach(function(result) { // 如果 result.id 看起来是一个数字(比如短哈希),那么 // 对象字面量的顺序就得不到保证。这种情况下,需要添加前缀 // 来确保 key 是字符串。 items['result-' + result.id] = <li>{result.text}</li>; }); return ( <ol> {items} </ol> ); }