如何写react 组件
创建React组件的基本方法
React组件可以通过函数式组件或类组件两种方式创建。以下是具体实现方法:
函数式组件
函数式组件是当前React开发中的首选方式,代码更简洁:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
使用ES6箭头函数写法:
const Welcome = (props) => {
return <h1>Hello, {props.name}</h1>;
}
类组件
类组件是传统写法,需要继承React.Component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件使用props
props是组件接收的外部参数:
function Greeting(props) {
return <p>Welcome, {props.userName}!</p>;
}
// 使用时
<Greeting userName="John" />
组件使用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>
);
}
类组件通过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>
);
}
}
组件生命周期
函数式组件使用useEffect Hook处理生命周期:
import { useEffect } from 'react';
function Example() {
useEffect(() => {
console.log('Component mounted');
return () => console.log('Component will unmount');
}, []);
return <div>Example</div>;
}
类组件通过生命周期方法处理:

class Example extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Example</div>;
}
}
事件处理
React事件使用驼峰命名法:
function ActionLink() {
const handleClick = (e) => {
e.preventDefault();
console.log('Link clicked');
};
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
样式处理
内联样式使用对象形式:
const divStyle = {
color: 'blue',
backgroundColor: 'lightgray'
};
function StyledComponent() {
return <div style={divStyle}>Styled text</div>;
}
使用CSS类名:
import './MyComponent.css';
function MyComponent() {
return <div className="my-style">Styled text</div>;
}
组件组合
组件可以组合使用形成更复杂的UI:
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
最佳实践
- 组件命名使用PascalCase
- 单一职责原则,保持组件小巧
- 合理拆分大型组件
- 使用PropTypes进行类型检查
- 优先使用函数式组件和Hooks
- 避免在render方法中进行复杂计算






