react如何创建组件
创建函数组件
函数组件是React中最简单的组件形式,使用JavaScript函数定义。函数接收props作为参数,返回React元素。
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数语法也可以用于创建函数组件:
const Greeting = (props) => {
return <h1>Hello, {props.name}</h1>;
};
创建类组件
类组件通过继承React.Component创建,必须包含render()方法:

class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
类组件可以包含状态(state)和生命周期方法:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
document.title = `Count: ${this.state.count}`;
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
使用Hooks创建组件
React 16.8引入Hooks后,函数组件也能使用状态和其他React特性:

import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
组件组合
组件可以嵌套使用,形成组件树:
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
<Counter />
</div>
);
}
组件导出与导入
通常将组件放在单独文件中导出:
// Greeting.js
import React from 'react';
export default function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
然后在其他文件中导入使用:
// App.js
import Greeting from './Greeting';
function App() {
return <Greeting name="World" />;
}






