react如何创建组件
创建 React 组件的常见方法
React 提供了多种创建组件的方式,以下是常用的几种方法:
函数组件 函数组件是最简单的 React 组件形式,它是一个纯 JavaScript 函数,接收 props 作为参数并返回 React 元素:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数组件 使用 ES6 箭头函数语法创建的函数组件:
const Greeting = (props) => {
return <h1>Hello, {props.name}</h1>;
};
类组件 使用 ES6 class 语法创建的组件,可以包含状态和生命周期方法:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件的最佳实践
使用 PropTypes 进行类型检查 为组件添加 prop 类型检查可以增加代码的健壮性:
import PropTypes from 'prop-types';
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequired
};
使用默认 props 为组件提供默认的 props 值:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
Greeting.defaultProps = {
name: 'Stranger'
};
现代 React 组件开发
使用 Hooks 的函数组件 React 16.8 引入的 Hooks 允许函数组件使用状态和其他 React 特性:
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>
);
}
使用 TypeScript 创建组件 使用 TypeScript 可以为组件添加类型安全:
interface GreetingProps {
name: string;
}
const Greeting: React.FC<GreetingProps> = ({ name }) => {
return <h1>Hello, {name}</h1>;
};
组件组织方式
将组件拆分为单独文件 每个组件通常放在单独的文件中,便于维护:
// Greeting.jsx
import React from 'react';
export default function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
使用组件组合 通过组合简单组件来构建复杂 UI:
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}






