react如何创建一个组件
创建React组件的方法
React组件可以通过函数式组件和类组件两种方式创建。以下是具体的实现方法:
函数式组件
函数式组件是使用JavaScript函数定义的组件,适用于无状态或使用Hooks的情况。
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数语法也可以用于创建函数式组件:
const Welcome = (props) => {
return <h1>Hello, {props.name}</h1>;
};
类组件
类组件是通过ES6类定义的组件,适用于需要状态和生命周期方法的情况。

class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件使用
创建组件后,可以在其他组件中像使用HTML标签一样使用它:
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}
组件属性
组件可以通过props接收数据:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// 使用组件并传递name属性
<Welcome name="Alice" />
组件状态
函数式组件使用useState Hook管理状态:

import { 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>
</div>
);
}
类组件使用this.state管理状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
组件生命周期
类组件可以通过生命周期方法处理不同阶段的逻辑:
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>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
函数式组件使用useEffect Hook处理生命周期:
import { useState, useEffect } from 'react';
function Clock() {
const [date, setDate] = useState(new Date());
useEffect(() => {
const timerID = setInterval(() => tick(), 1000);
return () => clearInterval(timerID);
}, []);
function tick() {
setDate(new Date());
}
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}






