如何写react 组件
React 组件的基本写法
React 组件分为函数组件和类组件两种形式。以下是两种组件的写法示例:
函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件 Props 的使用
Props 是从父组件传递给子组件的数据。在组件内部通过 props(函数组件)或 this.props(类组件)访问:
function Greeting(props) {
return <p>Hello, {props.userName}!</p>;
}
// 使用组件
<Greeting userName="Alice" />
组件 State 的管理
State 是组件内部的状态数据。函数组件使用 useState Hook,类组件使用 this.state:
函数组件
import { 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 Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
生命周期方法(类组件)
类组件可以使用生命周期方法,如 componentDidMount、componentDidUpdate 等:
class Example extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
render() {
return <div>Lifecycle Example</div>;
}
}
使用 Hooks(函数组件)
Hooks 是函数组件中用于状态管理和副作用处理的 API:
import { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Seconds: {seconds}</div>;
}
事件处理
React 事件处理使用驼峰命名法,如 onClick、onChange:
function Button() {
const handleClick = () => {
alert('Button clicked');
};
return <button onClick={handleClick}>Click Me</button>;
}
条件渲染
根据条件渲染不同内容:
function Greeting({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>;
}
列表渲染
使用 map 渲染列表:
function NumberList({ numbers }) {
return (
<ul>
{numbers.map(number => (
<li key={number}>{number}</li>
))}
</ul>
);
}
组件组合
通过组合多个组件构建复杂 UI:
function App() {
return (
<div>
<Header />
<Content />
<Footer />
</div>
);
}
以上是 React 组件的基本写法和常见用法,可以根据实际需求选择函数组件或类组件,并结合 Hooks 和生命周期方法实现更复杂的功能。







