javascript - React 在使用 React.Children.map 时会自动处理键吗?

标签 javascript reactjs

我很清楚 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

而第二个不产生任何。所以我有两个问题:

  1. React.Children.map 是否为我们通过它的元素自动生成键?
  2. 如果上述问题的答案是肯定的,那么是否可以保证 key 在重新呈现期间保持唯一且一致?我的意思是一致的,重新排序的元素在通过它时会产生相同的键

最佳答案

React.Children.map takes into account the key 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/

相关文章:

javascript - 模拟一个 "ontype"事件

javascript - 重新格式化对象

javascript - 如何在 react-router 2.0.0-rc5 中获取当前路由

ruby-on-rails - 检查 HyperSpec 中的项目是否为 "clickable"

javascript - 导入的变量未翻译

reactjs - redux 工具包使用 typescript 模拟商店

javascript - 解释为什么在 Javascript 中 false 和 modulus 总是等同于 true

javascript - 将正则表达式存储在集合对象中?

javascript - emberjs 嵌套 {{#each}} 不起作用

javascript - 使用 create-react-app 时如何获取 electro.js 文件的 typescript