react-intl:如何在不通过“ this.props.intl”的情况下更新子组件

时间:2019-01-17 06:46:55

标签: reactjs react-intl

当我从父组件使用intl库更改语言对象时,我需要将intl={this.props.intl}传递给子组件以进行更新。我正在使用FormattedMessage id="example"this.props.intl.formatMessage({ id: "example" })。我有一系列父子组件。因此,我需要多次将intl作为道具传递给每个孩子或某个组件。如果我需要更新子组件,则需要在每个子组件中传递intl。我需要一个解决方案。我不想在每个子组件中传递this.props.intl。

2 个答案:

答案 0 :(得分:0)

当您必须通过多个子链传递道具时,请使用上下文。

Here是CodeSandbox的示例。

关于何时以及如何使用上下文,请查看this文档。

答案 1 :(得分:0)

考虑使用Context API,当您想要共享组件树共有的内容时,可以使用它。

也请检查https://hackernoon.com/how-do-i-use-react-context-3eeb879169a2