类组件内部的功能组件 [英] Functional Components inside class components
问题描述
当前,我有一个类组件,其中包含充当JSX中组件的功能。
Currently I have a class component that contains functions that act as components in my JSX.
示例:
class MyComponent extends React.Component {
MySubComponent = (props) => {
if (props.display) {
return <p>This text is displayed</p>
}
}
render() {
return (
<this.MySubComponent display={true} />
)
}
}
以这种方式调用组件有什么影响吗?
Are there any repercussions to calling components this way? Also is there a term for this?
推荐答案
这会导致创建新的 MySubComponent $ c $每个
MyComponent
实例的c>函数,这不是很有效的方法。
This results in creating new MySubComponent
function for each MyComponent
instance, which is not very efficient way of doing this.
可能只有将 MySubComponent
作为 MyComponent
方法的两个好处。
There may be only two benefits of having MySubComponent
as MyComponent
method.
其中之一是 MySubComponent
可以替换为 MyComponent
子类中的另一种实现,而无需修改 render
函数。这不是React惯用的做法,因为它促进了功能方法而不是OOP。
One of them is that MySubComponent
can be replaced with another implementation in MyComponent
subclass without modifying render
function. This isn't idiomatic to React because it promotes functional approach instead of OOP.
另一个是 MySubComponent
可以访问 MyComponent
实例及其属性。这导致设计问题,因为两个组件紧密耦合。
Another is that MySubComponent
can access MyComponent
instance and its properties. This results in design problem because two components are tightly coupled.
这两个参数在React开发中都不是很重要的。除非有特定的需求要求 MySubComponent
成为 MyComponent
的一部分,否则不应将前者定义为实例后者的方法。可能只是这样:
Neither of these arguments is substantial in React development. Unless there are specific needs that require MySubComponent
to be a part of MyComponent
, the former shouldn't be defined as instance method of the latter. It could be just:
const MySubComponent = (props) => {
if (props.display) {
return <p>This text is displayed</p>
}
}
class MyComponent extends React.Component {
render() {
return (
<MySubComponent display={true} />
)
}
}
这篇关于类组件内部的功能组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!