React 中的类组件概述

类语法是定义一个 React 组件的最常见方式之一,虽然比功能语法更有说法,但它提供了更大的控制,以生命周期绑架的形式。

<$>[注]本指南假定 Babel 已正确配置为 React. 如果您正在使用 create-react-app,则此情况已经发生了。

创建一个类组件

创建一个类组件非常简单;只需定义一个扩展组件并具有渲染函数的类。

 1// MyComponent.js
 2import React, { Component } from 'react';
 3
 4class MyComponent extends Component {
 5  render() {
 6    return (
 7      <div>This is my component.</div>
 8    );
 9  }
10}
11
12export default MyComponent;

从那里,你可以在任何其他组件中使用它。

 1// MyOtherComponent.js
 2import React, { Component } from 'react';
 3import MyComponent from './MyComponent';
 4
 5class MyOtherComponent extends Component {
 6  render() {
 7    return (
 8      <div>
 9        <div>This is my other component.</div>
10        <MyComponent />
11      </div>
12    );
13  }
14}
15
16export default MyOtherComponent;

您不必为每个文件定义一个组件,但这可能是一个好主意。

使用 Props

事实上,‘MyComponent’并不太有用;它总是会做同样的事情. 幸运的是,React允许向具有类似HTML属性语法的组件传递副本。

1<MyComponent myProp="This is passed as a prop." />

然后可以通过this.props访问优惠。

1class MyComponent extends Component {
2  render() {
3    const {myProp} = this.props;
4    return (
5      <div>{myProp}</div>
6    );
7  }
8}

<$>[注] 包装在子中的变量将作为字符串进行渲染。

使用国家

类组件对功能组件的优点之一是访问组件状态。

1class MyComponent extends Component {
2  render() {
3    const {myState} = this.state || {};
4    const message = `The current state is ${myState}.`;
5    return (
6      <div>{message}</div>
7    );
8  }
9}

但是,由于它没有被设置在任何地方,所以this.state将是无效的,所以这个例子并不真正有用。

使用生命周期胡克

类组件可以定义在组件生命周期中执行的函数.共有七种生命周期方法:componentWillMount、componentDidMount、componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、componentDidUpdate、componentWillUnmount。

 1class MyComponent extends Component {
 2  // Executes after the component is rendered for the first time
 3  componentDidMount() {
 4    this.setState({myState: 'Florida'});
 5  }
 6
 7  render() {
 8    const {myState} = this.state || {};
 9    const message = `The current state is ${myState}.`;
10    return (
11      <div>{message}</div>
12    );
13  }
14}

<$>[注意]「this.state」不應直接分配,而應使用「this.setState」代替。

<$>[注]「this.setState」不能在「render」中使用。

Published At
Categories with 技术
Tagged with
comments powered by Disqus