组件如何使用react
使用 React 组件的基本方法
React 组件是构建用户界面的独立模块,分为函数组件和类组件两种形式。以下是具体使用方法:
函数组件 函数组件是最简单的形式,接收 props 并返回 React 元素:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件
类组件通过继承 React.Component 实现,具有生命周期方法:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件组合与嵌套
组件可以相互嵌套使用,形成树状结构:
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}
Props 的使用
Props 是组件的输入参数,不可变:
function Greeting(props) {
return <p>{props.message}</p>;
}
// 使用时
<Greeting message="Welcome back!" />
State 管理
类组件使用 this.state 管理内部状态:

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <div>{this.state.count}</div>;
}
}
函数组件使用 useState Hook:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return <div>{count}</div>;
}
生命周期方法(类组件)
重要生命周期方法示例:
class Example extends React.Component {
componentDidMount() {
// 组件挂载后执行
}
componentDidUpdate() {
// 组件更新后执行
}
componentWillUnmount() {
// 组件卸载前执行
}
}
事件处理
处理用户交互事件:

function Button() {
function handleClick() {
console.log('Clicked');
}
return <button onClick={handleClick}>Click</button>;
}
条件渲染
根据条件显示不同内容:
function Greeting(props) {
if (props.isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
列表渲染
使用 map() 渲染列表:
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) => (
<li key={number.toString()}>{number}</li>
))}
</ul>
);
}
组件间通信
父组件通过 props 传递数据给子组件:
function Parent() {
const data = "Hello";
return <Child message={data} />;
}
function Child(props) {
return <p>{props.message}</p>;
}
子组件通过回调函数与父组件通信:
function Parent() {
function handleChildClick(data) {
console.log(data);
}
return <Child onClick={handleChildClick} />;
}
function Child(props) {
return <button onClick={() => props.onClick('Data')}>Click</button>;
}






