问题
I'm trying to render a component recursively. On each recursive call I subtract 10 px from the dimensions. I expect a series of nested divs, each one 10px smaller. When the height and width reach 10px, the component should return null, so that is my base case.
Instead of expected result, I've got nothing. No errors in the terminal, no errors in the dev tools, just a page that is frozen.
Any thoughts?
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:
The issue is here:
<RecurentDiv width={style.width} height={style.height} />
//^^^^^^ ^^^^^^
style.width
is a string, not a number: ${width - 10}px
. The code is doing "100px" - 10
which evaluates to NaN
, which is then passed into the next RecurentDiv
's props. The base case is never reached.
Instead, pass width
and height
numbers directly into the recursive component, subtracting the reduction amount to approach the base case.
Here's a minimal, complete example:
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>
来源:https://stackoverflow.com/questions/60288750/how-to-render-recursive-component-in-react