如何写react组件
创建React组件的基本方法
React组件可以通过函数式组件或类组件两种方式创建。函数式组件是当前推荐的方式,因其简洁性和Hooks的支持。
函数式组件示例
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
使用Props传递数据
Props是组件间传递数据的主要方式,具有只读特性。父组件通过属性传递数据,子组件通过props接收。
function Welcome(props) {
return <h1>Welcome to {props.appName}</h1>;
}
// 使用组件
<Welcome appName="My React App" />
管理组件状态
函数式组件使用useState Hook管理状态,类组件使用this.state和this.setState。
函数式组件状态管理
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
处理事件
React事件处理采用驼峰命名法,需要传递函数而非字符串。
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
生命周期方法(类组件)
类组件提供生命周期方法用于在不同阶段执行代码,函数式组件使用useEffect Hook替代。
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
条件渲染
根据条件决定渲染内容的常用模式包括if语句、三元运算符和逻辑与运算符。
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<h1>Welcome back!</h1>
) : (
<h1>Please sign up.</h1>
)}
</div>
);
}
列表和Keys
使用map()方法渲染列表时,每个列表项需要唯一的key prop。
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
return <ul>{listItems}</ul>;
}
组件组合
通过组合多个简单组件构建复杂UI,推荐使用children prop实现组件包含。

function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}
function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
);
}






