如何实现react组件开发
搭建开发环境
安装Node.js和npm/yarn,确保环境支持React开发。使用create-react-app快速初始化项目:
npx create-react-app my-app
cd my-app
npm start
组件基础结构
React组件分为函数组件和类组件。函数组件示例:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
状态管理
类组件中使用state管理内部状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
}
函数组件使用Hooks管理状态:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
}
生命周期与副作用
类组件生命周期方法:
componentDidMount() {
// 组件挂载后执行
}
componentWillUnmount() {
// 组件卸载前清理
}
函数组件使用useEffect处理副作用:
useEffect(() => {
// 相当于componentDidMount
return () => {
// 相当于componentWillUnmount
};
}, []);
组件通信
父组件通过props向子组件传递数据:
function Parent() {
return <Child message="Hello" />;
}
function Child(props) {
return <p>{props.message}</p>;
}
子组件通过回调函数与父组件通信:
function Parent() {
const handleClick = (data) => {
console.log(data);
};
return <Child onClick={handleClick} />;
}
function Child({ onClick }) {
return <button onClick={() => onClick('Data')}>Click</button>;
}
样式处理
内联样式:
<div style={{ color: 'red' }}>Text</div>
CSS模块化:
import styles from './Button.module.css';
<button className={styles.error}>Button</button>
性能优化
使用React.memo缓存组件:
const MemoComponent = React.memo(function MyComponent(props) {
// 只有props改变时才会重新渲染
});
使用useCallback/useMemo避免不必要的计算:
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);






