React中如何在input的value属性中使用FormattedMessage?
如何在input的value属性中使用FormattedMessage
你直接把<FormattedMessage>组件传给input的value属性是行不通的——value需要纯字符串,而<FormattedMessage>是React组件,最终会被转为React元素对象而非字符串,所以页面只会显示[object Object]这类无效内容。
下面是两种更直接的替代方案:
方案1:函数组件用useIntl钩子
如果你的组件是函数式的,直接用react-intl的useIntl钩子获取格式化后的字符串:
import { useIntl } from 'react-intl'; // 组件内部 const intl = useIntl(); return ( <div className='flow_chooser actions'> <input disabled={model.isButtonDisabled} onClick={() => model.redirectTo(new_event_path(this.locale))} className='submit' type="submit" value={intl.formatMessage({ id: "get_started", defaultMessage: 'Get Started' })} /> </div> );
方案2:类组件用injectIntl高阶组件
如果是类组件,通过injectIntl把intl对象注入props,再调用formatMessage:
import { injectIntl, InjectedIntlProps } from 'react-intl'; // 定义props类型 interface YourComponentProps extends InjectedIntlProps { // 你的其他props定义 } class YourComponent extends React.Component<YourComponentProps> { render() { const { intl } = this.props; return ( <div className='flow_chooser actions'> <input disabled={model.isButtonDisabled} onClick={() => model.redirectTo(new_event_path(this.locale))} className='submit' type="submit" value={intl.formatMessage({ id: "get_started", defaultMessage: 'Get Started' })} /> </div> ); } } // 用injectIntl包装组件导出 export default injectIntl(YourComponent);
另外你用的<FormattedMessage>嵌套回调的写法本身是官方认可的有效方式,要是觉得结构不够简洁,上面两种直接生成字符串的方案会更直观。
内容的提问来源于stack exchange,提问作者dev0717
相关产品推荐
相关产品推荐

