- // 方式一:
- function Welcome(props) {
- return <h1>Hello, {props.name}h1>;
- }
-
- // 方式二:
- class Welcome extends React.Component {
- render() {
- return <h1>Hello, {this.props.name}h1>;
- }
- }
上述函数就是一个react组件,因为它接收唯一带有数据的“props”对象,并返回一个React元素。这类组件被称为“函数组件”,因为其本质上就是JavaScript函数
特征:
1、本身是一个函数
2、接收props(属性对象)
3、返回React元素
- const element = <Welcome name="Sara" />;
- ReactDOM.render(
- element,
- document.getElementById('root')
- );
无论是通过哪种方式声明出来的(函数声明 和 class声明),都是坚决不能修改自身的props的。
所有React组件都必须像纯函数一样保护它们的props不被更改
纯函数:
在函数中不会尝试更改入参,且多次调用下相同的入参始终返回相同的结果