react如何实现组件
React 组件实现方法
React 组件是构建用户界面的核心单元,分为函数组件和类组件两种形式。以下是具体实现方式:
函数组件实现
函数组件是推荐使用的现代写法,通过纯函数定义:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
箭头函数写法更简洁:
const Greeting = (props) => <h1>Hello, {props.name}</h1>;
带状态的函数组件需使用 Hooks:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
类组件实现
传统类组件写法需要继承 React.Component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
带状态的类组件:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<button onClick={this.handleClick}>
Clicked {this.state.count} times
</button>
);
}
}
组件组合方式
组件可以嵌套组合使用:
function App() {
return (
<div>
<Greeting name="Alice" />
<Counter />
</div>
);
}
组件间通信
父组件通过 props 向子组件传递数据:
function Parent() {
const data = "Message from parent";
return <Child message={data} />;
}
function Child({ message }) {
return <p>{message}</p>;
}
子组件通过回调函数与父组件通信:
function Parent() {
const handleChildClick = (msg) => {
console.log(msg);
};
return <Child onClick={handleChildClick} />;
}
function Child({ onClick }) {
return <button onClick={() => onClick('Child clicked')}>Click</button>;
}
生命周期管理
函数组件使用 useEffect 处理生命周期:
import { useEffect } from 'react';
function Timer() {
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer); // 清理函数
}, []);
return <div>Timer is running</div>;
}
类组件使用原生生命周期方法:
class Timer extends React.Component {
componentDidMount() {
this.timer = setInterval(() => console.log('tick'), 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return <div>Timer is running</div>;
}
}






