gpt4 book ai didi

javascript - react : parent component props in child without passing explicitly

转载 作者:行者123 更新时间:2023-12-03 13:42:46 25 4
gpt4 key购买 nike

是否可以让父组件的 props 在子组件中可用而不将它们向下传递?

我正在尝试实现一个提供程序模式,以便访问其子组件中的所有提供程序 Prop 。例如:

假设下面的提供程序组件 FetchProvider 将自行获取数据和主题 Prop ,并且当它包含任何子组件时,我想访问 Prop “data”和“theme”在子组件中也是如此。我们怎样才能实现它?

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
}
}

如果我尝试使用以下组件。

<FetchProvider>
<ChildComponent name="some value"/> //how can we access parent component props here? without passing them down
<FetchProvider/>

最佳答案

这正是react context就是这样。

Consumer 可以访问 Provider 公开的数据,无论嵌套的深度如何。

// 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>
);
}

这是一个小running example :

注意这是 React v16 上下文 API。

关于javascript - react : parent component props in child without passing explicitly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com