如何使用react组件
创建 React 组件
React 组件分为函数组件和类组件两种形式。函数组件是简单的 JavaScript 函数,类组件则继承自 React.Component。
函数组件示例
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 App() {
return <Greeting name="React" />;
}
使用 State 管理内部状态
State 用于存储组件的内部状态,类组件通过 this.state 和 this.setState 管理,函数组件使用 useState Hook。
类组件 State 示例
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
函数组件 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>
);
}
生命周期方法(类组件)
类组件提供生命周期方法,如 componentDidMount、componentDidUpdate 和 componentWillUnmount。
class LifecycleExample extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Lifecycle Example</div>;
}
}
使用 Hooks(函数组件)
Hooks 是函数组件的扩展功能,如 useState、useEffect 和 useContext。
useEffect 示例
import { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Seconds: {seconds}</div>;
}
组件组合与复用
通过组合多个组件构建复杂 UI,推荐使用 props 和 children 实现复用。
function Card({ title, children }) {
return (
<div className="card">
<h2>{title}</h2>
<div className="content">{children}</div>
</div>
);
}
function App() {
return (
<Card title="Welcome">
<p>This is the card content.</p>
</Card>
);
}
处理事件
React 事件使用驼峰命名(如 onClick),直接传递函数作为处理程序。
function ButtonClick() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
条件渲染
使用 JavaScript 条件语句(如 if 或三元运算符)控制组件渲染。
function Greeting({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>;
}
列表渲染
使用 map 方法渲染动态列表,并为每个项添加唯一的 key。

function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}






