react如何写组件
React 组件的写法
React 组件可以通过函数组件和类组件两种方式编写。以下是常见的写法:
函数组件
函数组件是使用 JavaScript 函数定义的组件,适用于简单的 UI 渲染。
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
箭头函数写法:
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
类组件
类组件继承 React.Component,适用于需要状态管理和生命周期方法的场景。
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
组件状态管理
函数组件使用 useState Hook 管理状态:
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>
);
}
类组件通过 this.state 和 this.setState 管理状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
组件生命周期
类组件可以通过生命周期方法(如 componentDidMount、componentDidUpdate)处理副作用:
class Example extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
render() {
return <div>Lifecycle Example</div>;
}
}
函数组件使用 useEffect Hook 替代生命周期:
import { useEffect } from 'react';
function Example() {
useEffect(() => {
console.log('Component mounted or updated');
return () => {
console.log('Component will unmount');
};
}, []);
return <div>Effect Example</div>;
}
组件通信
父组件通过 props 向子组件传递数据:
function Parent() {
return <Child message="Hello from Parent" />;
}
function Child(props) {
return <p>{props.message}</p>;
}
子组件通过回调函数向父组件传递数据:
function Parent() {
const handleChildClick = (data) => {
console.log('Data from child:', data);
};
return <Child onClick={handleChildClick} />;
}
function Child({ onClick }) {
return <button onClick={() => onClick('Child data')}>Click Me</button>;
}
组件样式
内联样式:
function StyledComponent() {
return <div style={{ color: 'red', fontSize: '20px' }}>Styled Text</div>;
}
CSS 模块:
import styles from './Component.module.css';
function StyledComponent() {
return <div className={styles.text}>Styled Text</div>;
}
组件复用
通过高阶组件(HOC)复用逻辑:
function withLogger(WrappedComponent) {
return function(props) {
console.log('Rendered:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogger(MyComponent);
通过自定义 Hook 复用状态逻辑:
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
}
function CounterA() {
const { count, increment } = useCounter(0);
return <button onClick={increment}>Count: {count}</button>;
}
以上是 React 组件的主要写法,根据具体需求选择合适的实现方式。







