React-Intl:在嵌套组件中访问 formatMessage
React-Intl: access formatMessage in nested component
这个问题很简单,我不敢相信我无法为如此简单的情况找到解决方案(没有上下文)。
我正在使用 react-intl。
我有一个 App.jsx 和一个子组件 Index.jsx 和一个 SideBar.jsx 和一个 CreateNewSomething.jsx.
在每个组件中,命令
<FormattedMessage
id="new_object.fill_title"
defaultMessage='Please fill the "title" parameter'
/>
非常感谢 App.jsx
提供的 <IntlProvider>
不幸的是,我无法将 FormattedMessage
作为组件的状态值注入。
示例:
<Input
s={6}
label={label_dash_title}
style={style_items_form}
onChange={this.onDashTitleChange}
onKeyPress={this.newDashHandleEnterKey}
error= { this.state.title_error }
/>
当输入字段未填写(必填)时,我想打印一条错误消息。
不幸的是我不会写:
const error_message = <FormattedMessage
id="new_dash.fill_title"
defaultMessage='Please fill the "title" parameter'
/>
this.setState({"title_error" : error_message});
因为我得到 [object Object]
并且里面没有 属性 和我翻译的消息。
到处搜索,我发现我必须使用this.props.intl.formatMessage({id: 'new_dash.fill_title'});
但 this.props.intl 未定义。
我已经尝试在 App.jax 中包含:
import {addLocaleData, IntlProvider, injectIntl, intlShape} from 'react-intl';
但这没有什么区别。
我尝试将 intl 作为 props 传递给每个子组件,但 intl 在 App.jsx 中也未定义。
我不知道我的错误在哪里。
该模块的Wiki说明了方法,但没有说明如何使用。
解决方法很简单。您必须更改 React 组件的导出语法,然后 this.props.intl 将在组件中神奇地可用:
export default injectIntl(MyComponent); //WORKS!!!
不幸的是:
export default class injectIntl(MyComponent) extends React.Component //DOESN'T WORK
这个问题很简单,我不敢相信我无法为如此简单的情况找到解决方案(没有上下文)。
我正在使用 react-intl。 我有一个 App.jsx 和一个子组件 Index.jsx 和一个 SideBar.jsx 和一个 CreateNewSomething.jsx.
在每个组件中,命令
<FormattedMessage
id="new_object.fill_title"
defaultMessage='Please fill the "title" parameter'
/>
非常感谢 App.jsx
提供的<IntlProvider>
不幸的是,我无法将 FormattedMessage
作为组件的状态值注入。
示例:
<Input
s={6}
label={label_dash_title}
style={style_items_form}
onChange={this.onDashTitleChange}
onKeyPress={this.newDashHandleEnterKey}
error= { this.state.title_error }
/>
当输入字段未填写(必填)时,我想打印一条错误消息。 不幸的是我不会写:
const error_message = <FormattedMessage
id="new_dash.fill_title"
defaultMessage='Please fill the "title" parameter'
/>
this.setState({"title_error" : error_message});
因为我得到 [object Object]
并且里面没有 属性 和我翻译的消息。
到处搜索,我发现我必须使用this.props.intl.formatMessage({id: 'new_dash.fill_title'});
但 this.props.intl 未定义。
我已经尝试在 App.jax 中包含:
import {addLocaleData, IntlProvider, injectIntl, intlShape} from 'react-intl';
但这没有什么区别。
我尝试将 intl 作为 props 传递给每个子组件,但 intl 在 App.jsx 中也未定义。
我不知道我的错误在哪里。
该模块的Wiki说明了方法,但没有说明如何使用。
解决方法很简单。您必须更改 React 组件的导出语法,然后 this.props.intl 将在组件中神奇地可用:
export default injectIntl(MyComponent); //WORKS!!!
不幸的是:
export default class injectIntl(MyComponent) extends React.Component //DOESN'T WORK