7 React 的组件化思想

7 React 的组件化思想

React 是一个用于构建用户界面的 JavaScript 库,其核心思想是“组件化”。这一思想使得开发者能够将复杂的 UI 拆分成更小、更可管理的部分,每个部分称为一个 组件。在这一小节中,我们将深入探讨组件化的概念、优势以及如何创建组件。

1. 组件的定义

在 React 中,组件 是一个 JavaScript 函数或类,接受 props(属性)并返回一个 React 元素(描述应该在屏幕上呈现的内容)。组件可以是以下几种形式:

  • 函数组件:一个简单的 JavaScript 函数。
  • 类组件:一个继承自 React.Component 的 ES6 类。

示例:函数组件

1
2
3
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

示例:类组件

1
2
3
4
5
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

2. 组件的类型

2.1 单个组件

一个单独的组件只负责渲染界面的一部分。在实际的应用中,从简单的按钮到复杂的表格都是单个组件的表现。

2.2 组合组件

多个组件可以组合在一起,形成更复杂的 UI 结构。父组件可以通过 props 将数据传递给子组件。

示例:组合组件

1
2
3
4
5
6
7
8
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}

在这个例子中,App 是一个父组件,它组合了两个 Greeting 子组件。

3. 组件的状态(State)

组件除了可以接收外部数据(通过 props),还可以有内部状态(state),用于存储与该组件相关的数据。状态改变时,组件会重新渲染。

示例:使用状态的组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

increment = () => {
this.setState({ count: this.state.count + 1 });
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

在这个示例中,Counter 组件有一个状态 count,并提供一个按钮来增加计数。每当按钮被点击时,组件会更新状态并重新渲染。

4. 组件的生命周期

每个 React 组件都有一系列的生命周期事件,从组件的创建到更新,以及销毁。在类组件中,可以通过生命周期方法来管理这些阶段。

常见的生命周期方法

  • componentDidMount:组件挂载后调用。
  • componentDidUpdate:组件更新后调用。
  • componentWillUnmount:组件卸载前调用。

示例:生命周期方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}

componentDidMount() {
this.interval = setInterval(() => {
this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
}, 1000);
}

componentWillUnmount() {
clearInterval(this.interval);
}

render() {
return <p>Seconds: {this.state.seconds}</p>;
}
}

在这个示例中,Timer 组件每秒更新一次计时器。componentDidMount 用于启动定时器,而 componentWillUnmount 用于清理定时器。

5. 组件的自定义和复用

组件化带来的另一个好处是能够复用组件。我们可以创建通用的组件,并在不同的地方使用它们。例如,一个按钮组件可以根据不同的属性进行样式和行为的调整。

示例:可复用的按钮组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Button({ color, onClick, children }) {
return (
<button style={{ backgroundColor: color }} onClick={onClick}>
{children}
</button>
);
}

// 使用可复用的按钮组件
function App() {
return (
<div>
<Button color="blue" onClick={() => alert('Clicked!')}>Click Me</Button>
<Button color="red" onClick={() => alert('Clicked again!')}>Click Me Too</Button>
</div>
);
}

在这个例子中,Button 组件是可复用的,可以接受不同的颜色和点击事件的处理函数。

6. 小结

组件化是 React 核心理念之一,它允许开发者将复杂的 UI 拆分为更小、更易于管理的部分。通过组合、状态管理和生命周期方法,我们能够构建功能强大且高效的用户界面。

在接下来的章节中,我们将进一步探讨如何使用更高级的组件形式,例如 高阶组件自定义 Hook,以实现更多的功能和复用性。

8 从零到上手学习React框架教程

8 从零到上手学习React框架教程

小节:创建和使用React组件

在React中,组件是构建用户界面的基本单位。通过创建和使用组件,我们可以将UI拆分成独立、可复用的部分,这样每个部分可以独立进行管理。

1. 组件的类型

React 主要有两种类型的组件:

  • 函数组件:使用函数定义的组件。
  • 类组件:使用ES6类定义的组件。

1.1 函数组件

函数组件是最常用的组件类型,语法简单,适合大多数场景。

1
2
3
4
5
6
7
import React from 'react';

const MyComponent = () => {
return <h1>Hello, World!</h1>;
};

export default MyComponent;

在上面的例子中,MyComponent 是一个函数组件,它返回一个简单的 h1 元素。

1.2 类组件

类组件可以使用更复杂的功能,比如组件的生命周期方法。

1
2
3
4
5
6
7
8
9
import React, { Component } from 'react';

class MyClassComponent extends Component {
render() {
return <h1>Hello, World!</h1>;
}
}

export default MyClassComponent;

在这个例子中,MyClassComponent 是一个类组件,它也返回一个 h1 元素,但它可以包含更多的功能。

2. 创建组件

2.1 组件的基本结构

无论是函数组件还是类组件,其基本结构都包含一个 render 方法(对于类组件)或直接返回 JSX(对于函数组件)。示例代码如下:

  • 函数组件
1
2
3
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
  • 类组件
1
2
3
4
5
class GreetingClass extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

3. 使用组件

在使用组件时,可以通过 JSX 来引入我们创建的组件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React from 'react';
import Greeting from './Greeting'; // 导入函数组件
import GreetingClass from './GreetingClass'; // 导入类组件

const App = () => {
return (
<div>
<Greeting name="Alice" />
<GreetingClass name="Bob" />
</div>
);
};

export default App;

App组件中,我们使用了两个不同的组件 GreetingGreetingClass,并通过 props 向它们传递数据。

4. 组件的状态和生命周期

在某些情况下,我们需要管理组件的状态。这通常在类组件中实现,但函数组件也可以使用 React Hooks 来处理状态。

4.1 类组件的状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

increment = () => {
this.setState({ count: this.state.count + 1 });
};

render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

在这个 Counter 类组件中,我们使用 state 来保存 count,并通过按钮点击事件来增加计数。

4.2 函数组件的状态

使用 Hooks 在函数组件中管理状态:

1
2
3
4
5
6
7
8
9
10
11
12
import React, { useState } from 'react';

const CounterFunction = () => {
const [count, setCount] = useState(0);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

在这个示例中,我们使用 useState 来定义和更新 count 的状态。

5. 组件的样式

组件可以通过 className 属性应用CSS样式:

1
2
3
const StyledComponent = () => {
return <h1 className="my-title">Styled Hello!</h1>;
};

在CSS中,我们可以定义 .my-title 的样式,从而给我们的组件添加样式。

6. 小结

通过创建和使用组件,我们可以构建复杂的用户界面。React 提供了函数组件和类组件两种选择,开发者可以根据需求选择适合的组件类型。频繁使用 propsstate 来实现数据的流动和组件的交互是 React 开发中的重要部分。在后续的学习中,我们将深入探讨更复杂的组件之间的交互、组建生命周期以及高阶组件等内容。

组件的状态(State)和属性(Props)

组件的状态(State)和属性(Props)

1. 概述

在React中,组件是构建用户界面的基本单元。每个组件可以管理自己的 状态(State) 和接收来自父组件的 属性(Props)。理解这两者的区别和用法是学习React的关键部分。

2. 属性(Props)

2.1 什么是 Props

Props 是组件接受的输入,被用来传递数据和事件处理函数。它们是只读的,不能在组件内部修改。

2.2 如何使用 Props

要在组件中使用 props,可以直接通过组件的参数访问:

1
2
3
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

在父组件中使用 Greeting 组件时,可以传递 name 属性:

1
2
3
4
5
6
7
8
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}

2.3 Props 的特点

  • 只读props 是不可变的,子组件不应修改来自父组件的 props
  • 用于数据传递props 主要用于从父组件向子组件传递数据。

3. 状态(State)

3.1 什么是 State

State 是组件内部管理的数据,可以在组件生命周期内进行更改。与 props 不同,state 是可变的,通常用于处理组件内部需要跟踪的变化。

3.2 如何使用 State

要在函数组件中使用 state,需要使用 React 的 useState Hook。

3.2.1 引入 useState

首先,需要从 react 包中导入 useState

1
import React, { useState } from 'react';

3.2.2 创建状态

使用 useState 创建状态变量:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Counter() {
// 定义一个名为 count 的状态变量,初始值为 0
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

3.3 State 的特点

  • 可变state 是可以被修改的,通常通过调用 setState 函数。
  • 影响渲染:当 state 更新后,React 会重新渲染组件以反映最新的状态。

4. Props 与 State 的区别

  • 来源

    • props 是由父组件传递给子组件的。
    • state 是组件自身管理的。
  • 可变性

    • props 是只读的,子组件无法修改。
    • state 是可变的,组件可以更新自己内部的 state
  • 用途

    • props 用于从父到子的单向数据流。
    • state 用于处理组件内部的数据和逻辑。

5. 实际应用案例

结合 propsstate 的一个简单实例,创建一个按钮点击计数器,每次点击按钮时,计数器增加,同时通过 props 将当前计数传递给子组件进行展示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
<Display count={count} />
</div>
);
}

function Display(props) {
return <h2>Current Count: {props.count}</h2>;
}

export default Counter;

在以上示例中,Counter 组件通过 state 管理点击次数,并将该值通过 props 传递给 Display 组件以展示。

6. 总结

在React中,理解组件的 stateprops 是关键。state 用于管理内部数据,props 用于在组件之间传递信息。学会使用这两者,将帮助你构建更复杂和功能丰富的React应用。