react如何开发组件
React 组件开发基础
React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。
函数组件示例:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件 Props 的使用
Props 是组件的只读属性,用于父子组件通信:
function UserCard(props) {
return (
<div>
<h2>{props.user.name}</h2>
<p>{props.user.email}</p>
</div>
);
}
// 使用组件
<UserCard user={{ name: "Alice", email: "alice@example.com" }} />
组件 State 管理
使用 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>
);
}
生命周期与副作用处理
使用 useEffect 处理副作用和生命周期:
import { useEffect } from 'react';
function DataFetcher({ userId }) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(`/api/user/${userId}`)
.then(res => res.json())
.then(setData);
}, [userId]); // 依赖数组控制执行时机
}
组件样式方案
React 支持多种样式方案:
-
内联样式:

<div style={{ color: 'red', fontSize: 16 }}>Text</div> -
CSS Modules:
import styles from './Button.module.css';
function Button() { return Submit; }
3. Styled-components:
```jsx
import styled from 'styled-components';
const StyledButton = styled.button`
background: palevioletred;
color: white;
`;
function Button() {
return <StyledButton>Click</StyledButton>;
}
组件组合模式
通过组合实现复杂 UI:
function Layout({ header, sidebar, content }) {
return (
<div className="layout">
<div className="header">{header}</div>
<div className="main">
<div className="sidebar">{sidebar}</div>
<div className="content">{content}</div>
</div>
</div>
);
}
// 使用
<Layout
header={<Header />}
sidebar={<Navigation />}
content={<Article />}
/>
组件性能优化
常用优化手段:
-
React.memo 缓存组件:

const MemoizedComponent = React.memo(function MyComponent(props) { /* 使用 props 渲染 */ }); -
useCallback 缓存函数:
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); -
useMemo 缓存计算结果:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
组件测试方案
使用 Jest + Testing Library 测试组件:
import { render, screen } from '@testing-library/react';
import Button from './Button';
test('renders button with text', () => {
render(<Button>Click</Button>);
expect(screen.getByText('Click')).toBeInTheDocument();
});
组件文档规范
使用 PropTypes 或 TypeScript 定义组件接口:
import PropTypes from 'prop-types';
function Button({ text, onClick }) {
return <button onClick={onClick}>{text}</button>;
}
Button.propTypes = {
text: PropTypes.string.isRequired,
onClick: PropTypes.func
};
或使用 TypeScript:
interface ButtonProps {
text: string;
onClick?: () => void;
}
function Button({ text, onClick }: ButtonProps) {
return <button onClick={onClick}>{text}</button>;
}






