在我看来,这里有两个常见的选择:
- 传递回调函数(使用 useCallback 或其他方式创建):
...
function Parent() {
const [text, setText] = useState('');
// Can also just pass setText directly
function onClick() {
setText('new text');
}
return (
<Child onClick={onClick} />
);
}
function Child(props) {
return (
<button onClick={props.onClick}>Click Me</button>
);
}
优点:简单
- 使用 Context API 并使用状态
如果子级嵌套很深,为了避免道具钻探(并使状态易于其他组件使用),您可以使用ContextAPI:
TextProvider.js
...
const TextContext = createContext('');
export function TextProvider(children) {
const [text, setText] = useState('');
const value = {
text, setText
};
return <TextContext.Provider value={text}>
{children}
</TextContext.Provider>;
};
export function useText() {
const context = useContext(ClientContext);
if (context === undefined) {
throw new Error('useSocket must be used within a SocketProvider');
}
return context;
};
App.js(或任何呈现 <Parent /> 的文件) - 将 Parent 包装在提供程序中:
function App() {
return (
...
<TextProvider>
<Parent />
</TextProvider>
...
);
}
Child.js
function Child(props) {
const { text, setText } = useText();
function onClick() {
setText('hello'); // Will update "text" state on parent
}
return (
<button onClick={onClick}>Click Me</button>
);
}
优点:在将 props 传递给深度嵌套的组件时很有用。此处的这篇文章详细介绍了ContextAPI 的更多优点/缺点