为了在更大的组件中渲染更小的组件/jsx,可以采用多种方法。例如,考虑一下:
方法一:
function BigComponent(props) {
const renderSmallComponent1 = () => <div>{props.a}</div>;
const renderSmallComponent2 = () => <div>{props.b}</div>;
return (
<div>
{renderSmallComponent1()}
{renderSmallComponent2()}
</div>
)
}
方法二:function BigComponent(props) {
const smallComponent1 = <div>{props.a}</div>;
const smallComponent2 = <div>{props.b}</div>;
return (
<div>
{smallComponent1}
{smallComponent2}
</div>
)
}
方法三:function SmallComponent1({ a }) {
return <div>{a}</div>;
}
function SmallComponent2({ b }) {
return <div>{b}</div>;
}
function BigComponent(props) {
return (
<div>
<SmallComponent1 a={props.a} />
<SmallComponent2 b={props.b} />
</div>
)
}
我只是想了解这三个方面的区别这些是我理解的事情:
SmallComponent
是在另一个组件中呈现的 React 组件,因此它们将具有组件生命周期,而在方法 1 和 2 中,它们是简单的 jsx,没有生命周期,因此它们不会作为 React 组件安装/卸载 其他一些有用的文章:
更新 :似乎观察 1 是不正确的,因为它们中的所有 3 个仍将呈现为 react 组件,因此将具有组件生命周期。所以 react 会挂载/卸载它们。
更新 2 :不,观察 1 是正确的,方法 1 和 2 都被视为常规 jsx 作为 BigComponent 的一部分,它们不被视为具有生命周期的 react 组件。
更新 3 :
还有一种方法方法4:
function BigComponent(props) {
const SmallComponent1 = () => {
return <div>{props.a}</div>;
}
const SmallComponent2 = () => {
return <div>{props.b}</div>;
}
return (
<div>
<SmallComponent1 />
<SmallComponent2 />
</div>
)
}
这与方法 3 类似,但方法 3 与方法 4 在通过开发工具调试时在执行上略有不同。
最佳答案
方法二:
function BigComponent(props) {
const smallComponent1 = <div>{props.a}</div>;
const smallComponent2 = <div>{props.b}</div>;
return (
<div>
{smallComponent1}
{smallComponent2}
</div>
)
}
useMemo()
包裹它们。如果这些 smallComponents 的结果来自昂贵的计算。 方法三:
function SmallComponent1({ a }) {
return <div>{a}</div>;
}
function SmallComponent2({ b }) {
return <div>{b}</div>;
}
function BigComponent(props) {
return (
<div>
<SmallComponent1 a={props.a} />
<SmallComponent2 b={props.b} />
</div>
)
}
hooks
.关于javascript - react : jsx in a variable vs a function vs a separate component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67185279/