如何在 React 中渲染递归组件?

IT技术 reactjs recursion
2021-04-30 06:24:25

我正在尝试以递归方式呈现组件。在每次递归调用时,我从尺寸中减去 10 像素。我希望有一系列嵌套的 div,每个小 10px。当高度和宽度达到 10px 时,组件应该返回 null,所以这是我的基本情况。

而不是预期的结果,我什么都没有。终端中没有错误,开发工具中没有错误,只是一个页面被冻结。

有什么想法吗?

RecurentDiv.js

const RecurentDiv = ({ width, height }) => {
  const style = {
    width: `${width - 10}px`,
    height: `${height - 10}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  if (width < 10) return null; //base case

  return (
      <div style={style}>
        <RecurentDiv width={style.width} height={style.height} />
      </div>
  );
};

export default RecurentDiv;

App.js

<RecurentDiv width={100} height={100} />
1个回答

问题在这里:

<RecurentDiv width={style.width} height={style.height} />
                  //^^^^^^               ^^^^^^

style.width是一个字符串,而不是一个数字:${width - 10}px代码正在执行"100px" - 10它的计算结果为NaN,然后将其传递给 nextRecurentDiv的props。基本情况从未达到。

取而代之的是,通过widthheight直接数字到递归成分,减去减小量以接近基础案例。

这是一个最小的完整示例:

const RecurrentDiv = ({width, height}) => {
  const style = {
    width: `${width}px`,
    height: `${height}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  return width < 10 ? null : (
    <div style={style}>
      <RecurrentDiv width={width - 10} height={height - 10} />
    </div>
  );
};

ReactDOM.render(<RecurrentDiv width={100} height={100} />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.0/umd/react-dom.production.min.js"></script>