无法在 React 项目中显示分数。即使使用 mathjs 也会出现子错误

Can't display fractions in React project. Child error instead even with mathjs

我想创建自己的食谱转换器,需要部分量度,例如杯子和茶匙的分数。当我尝试将这些作为部分插入到对象中时,如下所示,它在网页上显示小数而不是所需的比率。

export const ingredients = [
{
    id: 1,
    name: 'rice wine vinegar (or sub apple cider vinegar)',
    category: 'Pickled Vegetables',
    portion: 2/3,
    unit: 'cup',
},

经过研究,我发现了 npm 模块 mathjs 并下载了它,试图解决我的问题。

但是在添加此代码后,(它似乎可以独立运行)

const math = require('mathjs')

math.config({
     number: 'Fraction'
})

然后是这段代码

export const ingredients = [
{
    id: 1,
    name: 'rice wine vinegar (or sub apple cider vinegar)',
    category: 'Pickled Vegetables',

//portion value has changed
    portion: math.fraction(`2/3`),
    unit: 'cup',
},

我从模块的 website 的 Fraction 示例中复制了它,我收到了错误消息,指出此对象不是有效的 React 子对象,而是使用数组。

根据我从网站上看到的内容,似乎在数组中没有这个值是完全可以的。

我也试过将 / 放在 '' 中,但 VS Code 不接受它

portion: 2'/'3,

文本编辑器解释说这是错误的语法,现在我不知所措。

我的代码有什么问题,我是否在正确的轨道上处理分数?

这是因为你只做了一半的格式化...

试试这个:

/* for readability let's declare two thirds first */
const twoThirds = math.format(math.fraction('2/3'), { fraction: 'ratio' })

export const ingredients = [
{
    id: 1,
    name: 'rice wine vinegar (or sub apple cider vinegar)',
    category: 'Pickled Vegetables',

//portion value has changed
    portion: twoThirds,
    unit: 'cup',
},

The MathJs example page shows all fraction options