React 组件是构建 React 应用程序的基本单元之一。组件可以是函数组件或类组件,它们可以接收输入(props)并返回一个 React 元素来描述在屏幕上看到的内容。在本章节中,我们将深入探讨 React 组件的 API,包括生命周期方法、状态管理以及事件处理等内容。
创建一个函数组件
函数组件是一个接收 props 对象作为参数并返回一个 React 元素的函数。以下是一个简单的函数组件示例:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}在上面的示例中,我们定义了一个名为 Welcome 的函数组件,它接收一个 name 属性并在页面上显示一个欢迎消息。
创建一个类组件
类组件是一个继承自 React.Component 类的 JavaScript 类。类组件可以包含状态和生命周期方法。以下是一个简单的类组件示例:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}在上面的示例中,我们定义了一个名为 Welcome 的类组件,它接收一个 name 属性并在页面上显示一个欢迎消息。
生命周期方法
React 组件具有一系列生命周期方法,这些方法可以让我们在组件的不同阶段执行特定的逻辑。常用的生命周期方法包括 componentDidMount、componentDidUpdate 和 componentWillUnmount 等。以下是一个使用生命周期方法的示例:
// www.javascriptcn.com code example
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState((state) => ({
seconds: state.seconds + 1
}));
}
render() {
return <div>Seconds: {this.state.seconds}</div>;
}
}在上面的示例中,我们定义了一个名为 Timer 的类组件,它在 componentDidMount 方法中启动一个定时器,并在 componentWillUnmount 方法中清除定时器。
状态管理
React 组件可以包含状态,状态可以通过 this.state 属性来访问。当状态发生变化时,组件会重新渲染以反映最新的状态。以下是一个简单的状态管理示例:
// www.javascriptcn.com code example
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState((state) => ({
count: state.count + 1
}));
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.increment()}>Increment</button>
</div>
);
}
}在上面的示例中,我们定义了一个名为 Counter 的类组件,它包含一个计数器状态和一个增加计数器值的方法。
以上是关于 React 组件 API 的介绍,接下来我们将深入探讨更多关于 React 的内容。