我很清楚 reasons为什么在 React 中创建动态子项时需要添加 key
Prop 。令我感兴趣的是以下两段代码的行为
这仅使用 Array#map 遍历 children
const App = () => {
return (
<Parent>
<span>Child 1</span>
<span>Child 2</span>
<span>Child 3</span>
</Parent>
);
};
const Parent = ({ children }) => {
return children.map(child => (
<div style={{ background: "lightblue" }}>{child}</div>
));
};
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
<div id="app">
这使用 React.Children.map
做同样的事情
const App = () => {
return (
<Parent>
<span>Child 1</span>
<span>Child 2</span>
<span>Child 3</span>
</Parent>
);
};
const Parent = ({ children }) => {
return React.Children.map(children, child => (
<div style={{ background: "lightblue" }}>{child}</div>
));
};
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
<div id="app">
第一个片段产生警告
Each child in an array or iterator should have a unique "key" prop
而第二个不产生任何。所以我有两个问题:
React.Children.map
是否为我们通过它的元素自动生成键?- 如果上述问题的答案是肯定的,那么是否可以保证 key 在重新呈现期间保持唯一且一致?我的意思是一致的,重新排序的元素在通过它时会产生相同的键
最佳答案
React.Children.map
takes into account thekey
that you have provided for the child components and adds a prefix to them, if the key is not provided to the children components, it adds a Implicit key determined by the index in the set while iterating to the mapped object
以下是 mapChildren
的摘录函数形式 React src
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (
typeof component === 'object' &&
component !== null &&
component.key != null
) {
// Explicit key
return escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
关于javascript - React 在使用 React.Children.map 时会自动处理键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50303465/