In React, can I define a functional component within the body of another functional component?(在Reaction中,我可以在另一个功能组件的主体内定义一个功能组件吗?)
问题描述
我开始看到我的一些团队编写以下代码,这让我质疑我们是否以正确的方式做事,因为我以前从未见过它这样写。
import * as React from "react";
import "./styles.css";
function UsualExample() {
return <h1>This is the standard example…</h1>
}
export default function App() {
const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>
return (
<div className="App">
<UsualExample />
<CustomComponent />
</div>
);
}
它看起来呈现得很好,我看不到任何直接的不利影响,但是我们为什么不应该从另一个组件中定义CustomComponent
功能组件有什么根本原因吗?
CodeSandbox示例: https://codesandbox.io/s/dreamy-mestorf-6lvtd?file=/src/App.tsx:0-342
推荐答案
这不是个好主意。每次App
重新呈现时,都会为CustomComponent创建一个全新的定义。它具有相同的功能,但是因为它是一个不同的引用,所以Reaction将需要卸载旧的引用并重新挂载新的引用。因此,您将强制Reaction在每次呈现时执行额外的工作,并且还将重置CustomComponent内的任何状态。
const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>
export default function App() {
return (
<div className="App">
<UsualExample />
<CustomComponent />
</div>
);
}
有时,您可能会在单个组件内执行一些重复的操作,并希望通过使用帮助器函数来简化代码。这没问题,但是您需要将其作为函数调用,而不是将其呈现为组件。
export default function App() {
const customCode = (): JSX.Element => <h1>But can I do this?</h1>
return (
<div className="App">
{customCode()}
<UsualExample />
{customCode()}
</div>
);
}
使用此方法,Reaction将比较<h1>
和<h1>
,因此不需要重新装入它。
这篇关于在Reaction中,我可以在另一个功能组件的主体内定义一个功能组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在Reaction中,我可以在另一个功能组件的主体内定义一个功能组件吗?


基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01