代码之家  ›  专栏  ›  技术社区  ›  gene b.

React:计算组件数量+用更新的总数重新渲染所有组件

  •  0
  • gene b.  · 技术社区  · 3 年前

    我有 <Box> 从父组件顺序创建的组件。最后每个 Box 需要展示 X of Y ,其中X是当前指数,Y是总和。

    例如

    <Box .. />
    <Box .. />
    <Box .. />
    RENDERED RESULTS:
    1 of 3
    2 of 3
    3 of 3
    

    这个问题有两个部分:(1)获取当前运行的索引,(2)重新渲染所有 盒子 渲染完所有组件后,将其与总数相加。

    我不知道从哪里开始,即使是问题(1)。假设在父母我有

    const [count, setCount] = useState(0);
    
    return (
        <Box index={count} />
        <Box index={count} />      
    );
    

    盒子 成分

    export default function Box(props) {
    
      (props.index)++;
    
      return (
        <div>
            Running Index: {props.index}
        </div>
    )
    

    }

    但这给了我一个错误 类型错误:“索引”是只读的

    0 回复  |  直到 3 年前
        1
  •  1
  •   Drew Reese    3 年前

    问题

    Props是不可变的,计数状态被声明为const,因此无论如何都不能重新分配值。

    解决方案

    父级应该/通常会知道它正在渲染什么。通常,人们会通过以下方式渲染一个数据数组 Array.prototype.map 在这里,您可以同时获得正在渲染的数组的长度 映射回调中的当前索引。

    const Box = ({ index, total }) => (
      <div>
        Running Index: {index} of {total}
      </div>
    );
    

    例子:

    const [boxData] = useState(initialState);
    
    ...
    
    {boxData.map((data, index) => (
      <Box index={index + 1} total={boxData.length} />
    ));
    

    如果你正在寻找更“自动化”的东西,那么你可以创建一个包装器组件来自动注入 index total 道具。它首先克隆组件,然后注入额外的道具。

    import { cloneElement, Children } from "react";
    
    const BoxWrapper = ({ children }) =>
      Children.map(children, (child, index) =>
        cloneElement(child, {
          index: index + 1,
          total: Children.count(children)
        })
      );
    

    现在你可以渲染孩子了 Box 组件:

    <BoxWrapper>
      <Box />
      <Box />
      <Box />
    </BoxWrapper>
    

    enter image description here

    演示

    Edit react-count-number-of-components-re-render-all-of-them-with-updated-total