【问题标题】:how to make a message without wrapping in span in react-intl如何在 react-intl 中不包含 span 的情况下发送消息
【发布时间】:2018-01-31 02:06:46
【问题描述】:

我对 yahoo/react-intl 有疑问,我想以字符串类型制作消息,但是当我使用 FormattedMessage 时,它​​给了我用 span 包裹的消息,这并不酷。 我尝试了 formatMessage ,但也没有用。 我非常感谢任何帮助或建议这是我的代码:

import React from 'react';
import {FormattedMessage} from 'react-intl';
export default {
    items: [
        {
            name: <FormattedMessage id='app.dashboard'/>,
            url: '/dashboard',
            icon: 'icon-speedometer',
            badge: {
                variant: 'info',
                text: 'New',
            },
        },
        {
            title: true,
            name:  <FormattedMessage id='app.dashboard'/>,
            // optional wrapper object
            wrapper: {
                // required valid HTML5 element tag
                element: 'strong',
                // optional valid JS object with JS API naming ex: { className: "my-class", style: { fontFamily: "Verdana" }, id: "my-id"}
                attributes: {},
            },
            // optional class names space delimited list for title item ex: "text-center"
            class: '',`enter code here`
        },

【问题讨论】:

  • 问题不是很清楚,您可以添加更多详细的代码
  • BEJGAM SHIVA PRASAD 看看​​我的代码在这里工作,但它给了我用 span 包裹的数据,我不喜欢它并且 formatMessage 没有工作...

标签: reactjs react-intl formatmessage


【解决方案1】:

在 jsx 中使用:

它被渲染为&lt;span&gt;:

<FormattedMessage id='app.dashboard'/>

它被渲染为&lt;option&gt;:

<FormattedMessage id='app.dashboard' children={msg=> <option>{msg}</option>}/>

或:

<FormattedMessage id='app.dashboard' tagName="option"/>

它被渲染到nothing:

<FormattedMessage id='app.dashboard' children={msg=> <>{msg}</>}/>

或:

<FormattedMessage  id="app.dashboard">{txt => txt}</FormattedMessage>

要在组件中使用它,您可以像这样使用formatMessage()

const App=()=>{
  const value = intl.formatMessage({ id: 'header.nav.login' });
  return(<div>{value}</>)
}

【讨论】:

    【解决方案2】:

    鉴于您自己注入了intl 上下文,那么您可以使用formatMessage 函数。

    例如,在您的情况下:

    items: [
      { 
        name: intl.formatMessage({id:'app.dashboard'});
      }
    ]
    

    要在您的组件中获取intl,您有两种选择:

    1. 从组件的上下文中获取它
    2. 使用injectIntl 将其放入您的道具中。

    如果您不在组件中,它会稍微难一些,但我只会将 id 而不是格式化消息放在 name 中,然后在可用时使用 react-intl 上下文。在这里,在使用并显示此项目列表的组件中。

    【讨论】:

      【解决方案3】:

      这里的解决方案是将 react-intl 升级到版本 3。

      在版本 3 中,&lt;FormattedMesage&gt;(以及类似的其他 react-intl 组件)正在渲染为 React.Fragment

      如果你想把它渲染成别的东西,你可以在IntlProvider上指定textComponent prop,例如:

      <IntlProvider textComponent="span" />
      

      查看Migration Guide (v2 -> v3)中的信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-14
        • 2014-01-28
        • 2022-01-04
        • 2022-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多