简体   繁体   English

使用 React 语言切换将 state 从一个组件传递到另一个组件

[英]Passing state from one component to another with React language switch

I am translating my React App with headless CMS.我正在用无头 CMS 翻译我的 React 应用程序。 I have a language switcher in my navbar and on each component has to be the specified language.我的导航栏中有一个语言切换器,每个组件都必须是指定的语言。

The language Switcher logic:语言切换器逻辑:

const [selected, setSelected] = useState('en-us');

const handleEnglish = () => {
    cookies.set('chosenLang', 'en-us');
    setSelected('en-us');
};

<button onClick={handleEnglish}>EN</button>

const handleFrench = () => {
    cookies.set('chosenLang', 'fr-fr');
    setSelected('fr-fr');
};

<button onClick={handleFrench}>FR</button>

And logic in component based on which the language is recognised (pretty simple):以及识别语言所基于的组件中的逻辑(非常简单):

{lang: selected}

This works, but just because the language switcher is in the same file as translated component.这可行,但只是因为语言切换器与已翻译组件位于同一文件中。 Once I created separate component for navbar (where is the lang switch) it does not work and I don't know how to pass the state of it to other components)一旦我为导航栏创建了单独的组件(语言开关在哪里),它就不起作用了,我不知道如何将它的 state 传递给其他组件)

I tried in my page component to do something like <Navbar {...selected} /> , how I would normally pass the props but no luck with that.我尝试在我的页面组件中执行诸如<Navbar {...selected} />之类的操作,我通常会如何传递道具,但没有运气。

Just use the context API, the selected language state is available only locally in that component.只需使用上下文 API,所选语言 state 仅在该组件中本地可用。

https://reactjs.org/docs/context.html#when-to-use-context https://reactjs.org/docs/context.html#when-to-use-context

You can do like this:你可以这样做:

https://codesandbox.io/s/languagecontext-example-t33pm https://codesandbox.io/s/languagecontext-example-t33pm

You can you context or redux, react-redux to share state between components across app.您可以上下文或 redux、react-redux 在应用程序的组件之间共享 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM