您实际上不会直接访问孩子来检索他们的状态。你在这里想要的是一个包含父组件的上下文。查看React Context API。简而言之,您可以创建一个“上下文”,其中包含需要在多个组件之间共享的状态。创建上下文后,还会使用该上下文创建 Provider。此提供程序是一个接受 value 属性的组件。此道具包含上下文中所有状态值和设置器函数的对象。 Provider 组件的子组件可以使用useContext 挂钩从Provider 的value 属性中检索值和函数。
代码示例:
MyContext.js
import React, {createContext, useState} from 'react';
// Create the context and give it default values
export const MyContext = createContext(defaultValuesObject);
// We create a component that wraps around the provider, and is stateful. The states and their setters are placed into the provider, which is then returned.
const MyProvider = (props) => {
const [firstName, setFirstName] = useState("")
const [lastName, setLastName] = useState("")
const dataToShare = {
firstName,
setFirstName,
lastName,
setLastName,
}
// Return the context provider with the data already inside, and fill the children.
return (
<MyContext.Provider value={dataToShare}>
{props.children}
</MyContext.Provider>
)
}
我们现在有了提供者。在父组件的代码中,使用 useContext 挂钩让组件可以访问存储在提供程序组件中的值和函数。
MyParentComponent.jsx
import React, {useContext} from 'react';
import MyProvider, { MyContext } from 'MyContext'
const MyComponent = (props) => {
// useContext returns the value stored in the provider so we can use it and the functions inside. The context is maintained inside the states in the provider.
const providerValue = useContext(MyContext)
// OR
const { firstName, setFirstName, lastName, setLastName } = useContext(MyContext)
return (
<div>
// Provide the first child component with the values and functions from the context
<MyChildComponentOne someProp={providerValue} />
// Provide the second child component with the values and functions from the context
<MyChildComponentTwo someProp={providerValue} />
// Provide the second third component with the values and functions from the context
<MyChildComponentThree someProp={providerValue} />
<div/>
)
}
现在,我们仍然无法在没有提供程序的情况下使用上下文,提供程序必须围绕为该特定上下文调用 useContext 的组件。假设在 App.jsx 内部使用 ParentComponent:
App.jsx
...imports and whatever other code you have in here
/// The jsx for the App component or whatever component calls MyParentComponent
return <div>
<MyProvider>
<MyParentComponent>
</MyProvider>
</div>
要重新迭代,您将子/父组件的状态取出,并将它们放入由上下文创建的提供程序中。 Provider 的子组件可以调用useContext 并访问Provider 的value 属性中的数据和函数。