react如何写组件
React 组件的编写方法
React 组件可以通过函数组件和类组件两种方式编写,以下是具体实现方法。
函数组件
函数组件是使用 JavaScript 函数定义的组件,适用于无状态或使用 Hooks 的场景。
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
使用箭头函数简化:
const Greeting = (props) => <h1>Hello, {props.name}</h1>;
类组件
类组件通过继承 React.Component 实现,适用于需要生命周期或状态的场景。
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
使用状态(Hooks)
在函数组件中使用 useState Hook 管理状态。
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
生命周期方法(类组件)
类组件可以通过生命周期方法处理组件不同阶段的行为。
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Seconds: {this.state.seconds}</div>;
}
}
事件处理
在组件中绑定事件处理函数。
function ButtonClick() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
条件渲染
根据条件动态渲染内容。
function UserGreeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;
}
列表渲染
使用 map 渲染列表数据。
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) => (
<li key={number.toString()}>{number}</li>
))}
</ul>
);
}
Props 类型检查
使用 PropTypes 进行类型检查。
import PropTypes from 'prop-types';
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
默认 Props
为组件设置默认属性值。
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
Greeting.defaultProps = {
name: 'Guest',
};
组合组件
通过组合多个组件构建复杂 UI。

function App() {
return (
<div>
<Greeting name="Alice" />
<Counter />
</div>
);
}
以上方法涵盖了 React 组件的基本编写方式,可以根据需求选择函数组件或类组件,并结合状态管理、生命周期和事件处理实现更复杂的功能。






