从有状态到无状态的反应组件(差异)

Jak*_*777 1 reactjs

我试图找出React Stateful组件和无状态组件之间的区别.

如我错了请纠正我:

所以,这是一个有状态的组件:

import React from "react";

export class Mycomponent extends React.Component {
    render() {
        return (

            <div>
                <p>My Component</p>
            </div>

        );
    }
}
Run Code Online (Sandbox Code Playgroud)

如何将无状态组件与上述组件区分开来?

Cha*_*man 6

react state-full组件通常具有类语法并扩展react组件基类.这使您可以访问反应生命周期方法,例如render,componentDidMount等.

另一方面,无状态功能组件只不过是返回jsx的函数.您不在反应生命周期中,并且无法访问组件基类方法.

这是无状态功能组件的一些示例代码.

export default function example() {
    return (
        <h1>This is where the jsx goes</h1>
    )
}
Run Code Online (Sandbox Code Playgroud)

我还应该指出,在无状态功能组件中,您可以通过将props参数传递给函数来访问props,就像这样.

export default function example(props) {
    return (
        <h1>{props.person.firstName}</h1>
    )
}
Run Code Online (Sandbox Code Playgroud)

但是在反应类中,你只需通过访问即可获得道具 this.props.whatever