类组件中的功能组件

Functional Components inside class components(类组件中的功能组件)
本文介绍了类组件中的功能组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Currently I have a class component that contains functions that act as components in my JSX.

Example:

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?

解决方案

This results in creating new MySubComponent function for each MyComponent instance, which is not very efficient way of doing this.

There may be only two benefits of having MySubComponent as MyComponent method.

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.

Another is that MySubComponent can access MyComponent instance and its properties. This results in design problem because two components are tightly coupled.

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} />
        )
    }
}

这篇关于类组件中的功能组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)