React中的类组件概述
来自菜鸟教程
类语法是定义 React 组件的最常用方法之一。 虽然比函数式语法更冗长,但它以生命周期钩子的形式提供了更多控制。
本指南假定 Babel 已为 React 正确配置。 如果您正在使用 create-react-app,则已经是这种情况。
创建类组件
创建一个类组件非常简单; 只需定义一个扩展 Component 并具有 render 功能的类。
// MyComponent.js
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>This is my component.</div>
);
}
}
export default MyComponent;
从那里,您可以在任何其他组件中使用它。
// MyOtherComponent.js
import React, { Component } from 'react';
import MyComponent from './MyComponent';
class MyOtherComponent extends Component {
render() {
return (
<div>
<div>This is my other component.</div>
<MyComponent />
</div>
);
}
}
export default MyOtherComponent;
您不必为每个文件定义一个组件,但这可能是个好主意。
使用道具
照原样, MyComponent 并不是非常有用; 它总是会渲染同样的东西。 幸运的是,React 允许使用类似于 HTML 属性的语法将 props 传递给组件。
<MyComponent myProp="This is passed as a prop." />
然后可以使用 this.props 访问道具。
class MyComponent extends Component {
render() {
const {myProp} = this.props;
return (
<div>{myProp}</div>
);
}
}
括在括号中的变量将呈现为字符串。
使用状态
类组件相对于功能组件的好处之一是访问组件状态。
class MyComponent extends Component {
render() {
const {myState} = this.state || {};
const message = `The current state is ${myState}.`;
return (
<div>{message}</div>
);
}
}
但是由于它没有在任何地方设置,this.state 将为空,所以这个例子并不是很有用。 这让我们……
使用生命周期钩子
类组件可以定义将在组件生命周期内执行的函数。 共有七种生命周期方法:componentWillMount、componentDidMount、componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、componentDidUpdate , 和 componentWillUnmount。 为简洁起见,仅演示一个。
class MyComponent extends Component {
// Executes after the component is rendered for the first time
componentDidMount() {
this.setState({myState: 'Florida'});
}
render() {
const {myState} = this.state || {};
const message = `The current state is ${myState}.`;
return (
<div>{message}</div>
);
}
}
不应直接分配 this.state。 请改用 this.setState。
this.setState 不能在 render 中使用。