如何使用react组件
创建 React 组件
React 组件可以通过函数或类的方式定义。函数组件适用于简单的 UI 展示,类组件适用于需要状态管理和生命周期控制的场景。
函数组件示例:
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:
function App() {
return <Welcome name="React" />;
}
子组件接收 Props:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
管理组件状态
状态(State)用于存储组件内部可变的数据,通常通过 useState Hook 或类组件的 this.state 管理。
使用 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 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>
);
}
}
处理组件生命周期
类组件可以通过生命周期方法(如 componentDidMount、componentDidUpdate)执行特定逻辑,函数组件则使用 useEffect Hook。
使用 useEffect Hook:
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Seconds: {seconds}</div>;
}
类组件生命周期方法:
class Timer extends React.Component {
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>;
}
}
组合组件
通过组合多个组件构建复杂 UI,将子组件嵌套在父组件中。
示例:
function Card(props) {
return <div className="card">{props.children}</div>;
}
function App() {
return (
<Card>
<h2>Title</h2>
<p>Content goes here.</p>
</Card>
);
}
使用事件处理
React 事件处理采用驼峰命名法(如 onClick),事件处理器通常绑定到组件方法或内联函数。
示例:
function Button() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
条件渲染
根据条件动态渲染组件内容,可以使用 if 语句、三元运算符或逻辑与(&&)操作符。
示例:
function Greeting({ isLoggedIn }) {
return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}
列表渲染
使用 map 方法渲染动态列表,每个列表项需分配唯一的 key 属性以优化性能。
示例:

function NumberList({ numbers }) {
return (
<ul>
{numbers.map(number => (
<li key={number.toString()}>{number}</li>
))}
</ul>
);
}






