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

时间:2020-02-18 20:13:07

标签: reactjs recursion

我正在尝试递归地渲染组件。在每个递归调用中,我从尺寸中减去10 px。我希望有一系列嵌套的div,每个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 个答案:

答案 0 :(得分:3)

问题在这里:

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

style.width是一个字符串,而不是数字:${width - 10}px。代码正在执行"100px" - 10,其结果为NaN,然后将其传递到下一个RecurentDiv的道具中。永远不会达到基本情况。

相反,将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.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>