[英]How can I render a different component based on a value from the Context API?
So I have this navigator component where depending on a value coming from another component, I need to show a different bottom navigation. 因此,我有这个导航器组件,在其中根据来自另一个组件的值,我需要显示一个不同的底部导航。
For now I am getting an error on the context consumer, here: 现在,我在上下文使用者上遇到了一个错误,这里:
import { ThemeProvider, ThemeConsumer } from '../context/some';
const SelectedRoute = () => (
<ThemeConsumer>
{context => (context ? MainTabNavigator : PickupNavigator)}
</ThemeConsumer>
);
export default createAppContainer(
createSwitchNavigator(
{
App: SelectedRoute,
},
),
);
This is the only thing I have to create context: 这是我创建上下文的唯一步骤:
const ThemeContext = React.createContext(0);
export const ThemeProvider = ThemeContext.Provider;
export const ThemeConsumer = ThemeContext.Consumer;
I am getting this warning: 我收到此警告:
Warning: Functions are not valid as a React child.
警告:函数作为React子元素无效。 This may happen if you return a Component instead of from render.
如果返回Component而不是从render返回,则可能会发生这种情况。 Or maybe you meant to call this function rather than return it.
或者,也许您打算调用此函数而不是返回它。
What can I do to render what I need correctly? 我该怎么做才能正确呈现我的需求?
You want to return JSX from the function given as child to ThemeConsumer
, not just return a component. 您想从作为
ThemeConsumer
给JSX返回给ThemeConsumer
,而不仅仅是返回一个组件。
const SelectedRoute = () => (
<ThemeConsumer>
{context => (context ? <MainTabNavigator /> : <PickupNavigator />)}
</ThemeConsumer>
);
I have not run the example, but just suggesting from the docs. 我没有运行示例,只是从文档中提出建议。 I thought the explanation was pretty clear but I could be wrong.
我以为解释很清楚,但我可能是错的。
Just define a context variable in a separate file, in your case like this: 只需在一个单独的文件中定义一个上下文变量,在这种情况下,如下所示:
export const IndexContext = React.createContext({
indexValue: value,
toggleNavigator: () => {},
});
In your component(which receives indexValue), you can use the context value and toggle accordingly: 在您的组件(接收indexValue)中,您可以使用上下文值并相应地进行切换:
<ThemeContext.Consumer>
{({indexValue, toggleNavigator}) => (
// your component which uses the theme
)}
</ThemeContext.Consumer>
Since your component A is a stateful component, you can handle changes and update the context value there. 由于组件A是有状态的组件,因此您可以在那里处理更改并更新上下文值。
class App extends React.Component {
constructor(props) {
super(props);
this.toggleIndex = () => {
this.setState({ index });
this.handleStateIndexChange();
MY_CONTEXT = index;
};
// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
index: index,
toggleIndex: this.toggleIndex,
};
}
render() {
// The entire state is passed to the provider
return (
<IndexContext.Provider value={this.state}>
<Content />
</IndexContext.Provider>
);
}
}
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.