react如何创建公共组件
创建公共组件的基本方法
在React中创建公共组件可以提高代码复用性和可维护性。公共组件通常放置在独立的目录中,例如src/components,并通过模块化方式导出。
定义组件文件结构
公共组件通常存放在独立的文件中,文件名采用PascalCase命名法。例如创建一个按钮组件:
// src/components/Button.jsx
import React from 'react';
const Button = ({ children, onClick, type = 'button' }) => {
return (
<button type={type} onClick={onClick}>
{children}
</button>
);
};
export default Button;
组件属性设计
公共组件应通过props接收外部数据和行为,保持组件的灵活性和可复用性。使用PropTypes或TypeScript定义组件接口:
import PropTypes from 'prop-types';
Button.propTypes = {
children: PropTypes.node.isRequired,
onClick: PropTypes.func,
type: PropTypes.oneOf(['button', 'submit', 'reset'])
};
组件样式处理
公共组件的样式可以通过CSS模块、styled-components或Tailwind等方式实现隔离:
// 使用CSS模块
import styles from './Button.module.css';
const Button = ({ children }) => (
<button className={styles.button}>{children}</button>
);
组件文档注释
为公共组件添加清晰的文档注释,说明组件的用途、props和示例用法:
/
* 通用按钮组件
* @param {Object} props - 组件属性
* @param {ReactNode} props.children - 按钮内容
* @param {Function} [props.onClick] - 点击事件处理函数
* @param {'button'|'submit'|'reset'} [props.type='button'] - 按钮类型
* @example
* <Button onClick={() => console.log('Clicked')}>Submit</Button>
*/
组件测试
为公共组件编写单元测试确保其行为符合预期:
// Button.test.jsx
import { render, screen } from '@testing-library/react';
import Button from './Button';
test('renders button with children', () => {
render(<Button>Click me</Button>);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
组件导出和使用
在components目录下创建index.js文件集中导出所有公共组件:
// src/components/index.js
export { default as Button } from './Button';
export { default as Input } from './Input';
其他组件使用时通过命名导入:
import { Button } from '../components';
组件性能优化
对于频繁使用的公共组件,使用React.memo避免不必要的重新渲染:

const Button = React.memo(({ children }) => {
return <button>{children}</button>;
});






