React 是一个用于构建用户界面的 JavaScript 库,它采用组件化的开发方式,将整个应用拆分成多个独立且可复用的组件。在 React 中,组件是构建用户界面的基本单元,每个组件都有自己的状态和属性。
创建组件
在 React 中,可以使用函数组件或类组件来创建组件。函数组件是一种简单的组件形式,只需要编写一个函数来返回 JSX 元素即可。以下是一个简单的函数组件示例:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}类组件是另一种常见的组件形式,需要继承自 React.Component 类,并实现一个 render 方法来返回 JSX 元素。以下是一个简单的类组件示例:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}使用组件
要在应用中使用组件,只需在 JSX 中像使用 HTML 标签一样使用组件标签即可。可以通过 props 属性向组件传递数据。以下是一个使用上述 Welcome 组件的示例:
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}在上面的示例中,我们在 App 组件中使用了两个 Welcome 组件,并通过 name 属性向组件传递了数据。
组件的生命周期
React 组件有生命周期方法,可以在组件的不同阶段执行特定的操作。常用的生命周期方法包括 componentDidMount、componentDidUpdate 和 componentWillUnmount。以下是一个生命周期方法的示例:
// www.javascriptcn.com code example
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}在上面的示例中,我们定义了一个 Clock 组件,利用 componentDidMount 和 componentWillUnmount 方法实现了定时更新时间的功能。
以上是关于 React 组件的简要介绍,组件是 React 应用的核心,合理地拆分组件能够提高代码的可维护性和复用性。在接下来的章节中,我们将深入探讨组件的更多用法和技巧。