问题描述
我想知道它是否是一种反模式,或者它是否会以某种方式影响组件来做这样的事情:
render() {const MyFuncComponent = ({ prop1, prop2 }) =>(//代码在这里)返回 (<div><MyFuncComponent prop1={something} prop2={else}/>
我想知道它是否是一种反模式,或者它是否会以某种方式影响组件来做这样的事情:
render() {const MyFuncComponent = ({ prop1, prop2 }) =>(//代码在这里)返回 (<div><MyFuncComponent prop1={something} prop2={else}/>
)}
我认为一般人们会避免在渲染中定义函数,但根据 这篇博文 这不一定是一个坏习惯.博客文章重点介绍了在渲染中定义的内联事件处理函数,但我猜它适用于渲染中定义的任何函数.在 render 中定义函数意味着每次调用 render 时都会产生重新定义它们的开销,但这可能不会造成明显的性能差异,具体取决于您的组件.
对于您给出的特定示例,我建议不要在渲染中定义另一个反应组件.如果您确实在 render 中定义了任何函数,它们应该与 render 正在执行的操作保持一致.在 render 中定义另一个组件或添加一堆函数会使代码变得笨拙且难以理解.
I want to know if it's an anti-pattern or if it affects the component somehow to do something like this:
render() {
const MyFuncComponent = ({ prop1, prop2 }) => (
// code here
)
return (
<div>
<MyFuncComponent prop1={something} prop2={else} />
</div>
)
}
I think in general people avoid defining functions in render but according to this blog post it is not neccesarily a bad practice. The blog post focuses on inline event handler functions being defined in render but I would guess it applies to any function defined in render. Defining functions in render means there is the overhead of redfining them each time render is called but that may not make a noticible performance difference depending on your component.
For the particular example you gave I would reccomend not to define another react component in render. If you do define any functions in render they should be cohesive to what render is doing. Defining another component or adding a bunch of functions inside of render can make in unwieldy and hard to understand what the code is doing.
这篇关于在 render() 函数中定义函数组件是一种反模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!