一、Props向下传递(Top-Down Propagation)
父组件通过props将其状态或数据传递给子组件。
父组件:
class ParentComponent extends React.Component {
state = { message: 'Hello World' };
render() {
return <ChildComponent message={this.state.message} />;
}
}
子组件;
class ChildComponent extends React.Component {
render() {
return <div>{this.props.message}</div>;
}
}
二、Callback函数
父组件向子组件传递一个回调函数,子组件在需要时调用这个函数与父组件通信。
父组件:
class ParentComponent extends React.Component {
handleData = (data) => {
console.log('Received from child:', data);
};
render() {
return <ChildComponent sendData={this.handleData} />;
}
}
子组件:
class ChildComponent extends React.Component {
someEvent = () => {
this.props.sendData('Data from child');
};
render() {
return <button onClick={this.someEvent}>Send Data to Parent</button>;
}
}
三、Lifting State Up(状态提升)
当多个组件需要共享状态时,可以将状态提升到它们共同的父组件中。
父组件:
class ParentComponent extends React.Component {
state = { sharedData: 'Shared Data' };
render() {
return (
<>
<ChildA sharedData={this.state.sharedData} />
<ChildB sharedData={this.state.sharedData} />
</>
);
}
}
子组件A和B:
class ChildComponent extends React.Component {
render() {
return <div>{this.props.sharedData}</div>;
}
}
四、 Context(上下文)
React的Context API允许你共享值给组件树中的所有组件,而不必显式地通过每个层级传递props
创建Context:
const MyContext = React.createContext(defaultValue);
提供Context值:
<MyContext.Provider value={/* 一些值 */}>
{/* 组件树 */}
</MyContext.Provider>
在子组件中使用Context:
class ChildComponent extends React.Component {
render() {
return (
<MyContext.Consumer>
{value => <div>{value}</div>}
</MyContext.Consumer>
);
}
}
或者使用useContext
钩子:
import { useContext } from 'react';
const ChildComponent = () => {
const value = useContext(MyContext);
return <div>{value}</div>;
};
五、Custom Hooks(自定义钩子)
自定义钩子允许你提取组件逻辑,使其可以在多个组件间重用。
自定义钩子:
function useCustomHook() {
const [state, setState] = useState(initialState);
// 钩子的逻辑...
return state;
}
在组件中使用自定义钩子:
const Component = () => {
const state = useCustomHook();
return <div>{state}</div>;
};
六、 Higher-Order Components(高阶组件)
高阶组件是React中的一个高级技术,它通过包装一个组件来扩展其功能。
高阶组件:
function enhanceComponent(WrappedComponent) {
return class extends React.Component {
// 扩展逻辑...
render() {
return <WrappedComponent {...this.props} />;
}
};
}
//使用高阶组件:
const EnhancedComponent = enhanceComponent(OriginalComponent);