React Functional组件:作为函数调用与作为组件调用 [英] React Functional component: calling as function vs. as component
问题描述
说我有一个功能组件:
const Foo = (props) => ( <div>{props.name}</div> );
直接作为函数调用有什么区别?
What is the difference between calling it directly as a function:
const fooParent = () => (
<div> {Foo({ name: "foo" })} </div>
)
将其称为组件:
const fooParent = () => (
<div> <Foo name="foo"/> </div>
)
我最感兴趣的是性能含义,React如何在内部对它们进行区别对待,也许对React Fiber中的情况可能有所不同,在那儿,我听到功能组件的性能有所提高.
I'm mostly interested in performance implications, how React treats them differently internally, and perhaps how things might be different in React Fiber, where I hear functional components got a performance boost.
推荐答案
将其作为函数调用要快得多,事实上,几个月前就进行了讨论.在这一点上,功能React组件不能是 PureComponents ,因此没有真正应用额外的优化给他们.
Calling it as a function is much faster, in fact there was a talk exactly about this few months ago. At this point functional react components can't be PureComponents so no extra optimizations really applied to them.
基本上可以将功能组件称为消除整个反应生命周期的函数.如果考虑一下,您可能甚至在现在的render方法中也使用了此技术.考虑一下:
Basically if you can call functional component as a function that eliminates whole react lifecycle. If you think about it you are probably using this technique inside your render method even right now. Consider this:
... some component ...
render() {
const tabHeaders =<TabHeaders>{this.props.tabs.map(this.renderTabHeader)}</TabHeader>;
const tabContents = <TabContents>{this.props.tabs.map(this.renderTabContent)}</TabContents>;
return (<div>
{this.props.tabsBelow?[tabContents, tabHeaders] : [tabHeaders, tabContents]}
</div>);
}
renderTabHeader方法返回一些反应组件,本来可以是功能组件,但在这种情况下,只是一些组件类方法.
renderTabHeader method returns some react components, and could've been functional components but in this case is just some component class method.
请参阅此文章以获取详细说明: https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f
See this article for detailed explanation: https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f
也请查看执行此操作的babel插件: https://babeljs.io/docs/plugins/transform-react-inline-elements
Also check out this babel plugin that is doing that: https://babeljs.io/docs/plugins/transform-react-inline-elements
这篇关于React Functional组件:作为函数调用与作为组件调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!