React:子组件中的父组件props无需显式传递 [英] React: parent component props in child without passing explicitly
问题描述
是否有可能使父级组件的道具在子级组件中可用,而无需将其传递下来.
Is it possible to have the props of the parent component to be available in child component without passing them down.
我正在尝试实现提供者模式,以便访问其子组件中的所有提供者道具.例如:
I am trying to implement a provider pattern, so that to access all the provider props in its child components. EX:
假设下面的提供程序comp FetchProvider
将自己获取数据和主题道具,并且当其包含任何子组件时,我都希望在其中访问道具"data"和"theme"子组件也是如此.我们如何实现呢?
Suppose the below provider comp FetchProvider
will fetch the data and theme props on its own, and when any child component is enclosed by it, i want access both props "data" and "theme" in the child component as well. How can we achieve it?
class FetchProvider
{
proptypes= {
data: PropTypes.shape({}),
theme: PropTypes.shape({})
}
render()
{
// do some
}
mapStateToProps()
{
return {data, theme};
}
}
class ChildComponent
{
proptypes= {
name: PropTypes.shape({})
}
render()
{
const{data, them} = this.props; // is this possible here?
// do some
}
}
,如果我尝试使用以下组件,则该组件.
and if i try to above components as below.
<FetchProvider>
<ChildComponent name="some value"/> //how can we access parent component props here? without passing them down
<FetchProvider/>
推荐答案
这正是反应上下文就是关于.
Consumer
可以访问 Provider
公开的数据,无论其嵌套的深度如何.
A Consumer
can access data the a Provider
exposes no matter how deeply nested it is.
// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
// Use a Provider to pass the current theme to the tree below.
// Any component can read it, no matter how deep it is.
// In this example, we're passing "dark" as the current value.
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton(props) {
// Use a Consumer to read the current theme context.
// React will find the closest theme Provider above and use its value.
// In this example, the current theme is "dark".
return (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} />}
</ThemeContext.Consumer>
);
}
这是一个小的正在运行的示例:
注意.这是react v16上下文API.
Note This is the react v16 context API.
这篇关于React:子组件中的父组件props无需显式传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!