react如何使用组件
使用组件的基本方法
在React中,组件是构建用户界面的核心单元。组件分为函数组件和类组件两种形式。
函数组件示例
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件导入与导出
组件通常定义在单独的文件中,通过ES6模块系统进行导入导出。
导出组件
// Greeting.js
export default function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
导入组件
// App.js
import Greeting from './Greeting';
function App() {
return <Greeting name="Alice" />;
}
组件属性传递
通过props向子组件传递数据。
function UserCard(props) {
return (
<div>
<h2>{props.user.name}</h2>
<p>{props.user.email}</p>
</div>
);
}
// 使用组件
<UserCard user={{ name: 'Bob', email: 'bob@example.com' }} />
组件状态管理
使用useState钩子管理函数组件的状态。
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 Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.interval = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
render() {
return (
<div>
Seconds: {this.state.seconds}
</div>
);
}
}
事件处理
组件中可以绑定事件处理函数。
function ButtonExample() {
function handleClick() {
alert('Button clicked!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
条件渲染
根据条件决定渲染内容。
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome back!</h1>
) : (
<h1>Please sign in.</h1>
)}
</div>
);
}
列表渲染
使用map方法渲染列表数据。
function NumberList({ numbers }) {
return (
<ul>
{numbers.map((number) => (
<li key={number.toString()}>
{number}
</li>
))}
</ul>
);
}
组件组合
通过组合多个简单组件构建复杂UI。
function App() {
return (
<div>
<Header />
<MainContent />
<Footer />
</div>
);
}






