【问题标题】:Separate a price/number by a comma in React在 React 中用逗号分隔价格/数字
【发布时间】:2020-09-15 13:01:37
【问题描述】:

我正在为我的投资组合克隆亚马逊。在 React 中有这样的价格:price={37.84}。我希望价格显示如下:price={37,84}。出现的价格是84。有没有办法将价格显示为37,84

代码:

<div className="home__row">
          <Product
            id="12321341"
            title="Learning React: Modern Patterns for Developing React Apps 2nd Edition"
            price={37,84}
            rating={5}
            image="https://images-na.ssl-images-amazon.com/images/I/51Kwaw5nInL._SX379_BO1,204,203,200_.jpg"
          />

产品组件:

import React from "react";
import "./Product.css";
import { useStateValue } from "./StateProvider";

function Product({ id, title, image, price, rating }) {
  const [{ basket }, dispatch] = useStateValue();

  const addToBasket = () => {
    // dispatch the item into the data layer
    dispatch({
      type: "ADD_TO_BASKET",
      item: {
        id: id,
        title: title,
        image: image,
        price: price,
        rating: rating,
      },
    });
  };

  return (
    <div className="product">
      <div className="product__info">
        <p>{title}</p>
        <p className="product__price">
          <small>€</small>
          <strong>{price}</strong>
        </p>
        <div className="product__rating">
          {Array(rating)
            .fill()
            .map((_, i) => (
              <p>????</p>
            ))}
        </div>
      </div>

      <img src={image} alt="" />

      <button onClick={addToBasket}>Add to Basket</button>
    </div>
  );
}

export default Product;

【问题讨论】:

  • 认为我们需要更多信息。 Product 组件有什么作用?
  • 产品组件已添加。

标签: reactjs comma price


【解决方案1】:

在 JavaScript 代码中支持使用逗号作为小数分隔符,您不能在数字文字中使用它。但是,您可以使用语言环境功能将数字格式化为字符串,例如使用数字的toLocaleString method:

> 37.84.toLocaleString("en-de");  // based on your profile
"37,84"

如果您确实尝试使用逗号,则它是 comma operator,您最终会得到最右边的值:

> 37,84
84

【讨论】:

    【解决方案2】:

    使用price={"37,84"} 将其显示为字符串。

    或者,如果您有一个包含价格的变量,请使用:

    price={price.replace('.', ',')}
    

    【讨论】:

      【解决方案3】:

      解决这个问题有两种方法,方法大同小异:将float转为string,替换dot。

      String(price).split(".").join(",")
      String(price).replace(".", ",")
      

      这应该可行:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-23
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        相关资源
        最近更新 更多