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中,我可以在另一个功能组件的主体内定义一个功能组件吗?
基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
