用来做format的组件

在我们需要格式化字符串的时候, 我们可以在render方法中去使用helper函数. 然而, 更好的方法是去使用一个组件去做这件事.

使用组件的做法

render函数的实现会更加的干净因为只会是一些组件的组合.

  1. const Price = (props) => {
  2. // toLocaleString 并不是React的API而是原生JavaScript的内置方法
  3. // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
  4. const price = props.children.toLocaleString('en', {
  5. style: props.showSymbol ? 'currency' : undefined,
  6. currency: props.showSymbol ? 'USD' : undefined,
  7. maximumFractionDigits: props.showDecimals ? 2 : 0
  8. });
  9. return <span className={props.className}>{price}</span>
  10. };
  11. Price.propTypes = {
  12. className: PropTypes.string,
  13. children: PropTypes.number,
  14. showDecimals: PropTypes.bool,
  15. showSymbol: PropTypes.bool
  16. };
  17. Price.defaultProps = {
  18. children: 0,
  19. showDecimals: true,
  20. showSymbol: true,
  21. };
  22. const Page = () => {
  23. const lambPrice = 1234.567;
  24. const jetPrice = 999999.99;
  25. const bootPrice = 34.567;
  26. return (
  27. <div>
  28. <p>One lamb is <Price className="expensive">{lambPrice}</Price></p>
  29. <p>One jet is <Price showDecimals={false}>{jetPrice}</Price></p>
  30. <p>Those gumboots will set ya back
  31. <Price
  32. showDecimals={false}
  33. showSymbol={false}>
  34. {bootPrice}
  35. </Price>
  36. bucks.
  37. </p>
  38. </div>
  39. );
  40. };

不使用组件的做法.

代码量更少, 但是让render方法看起来不那么干净(作者个人感觉, 哈哈)

  1. function numberToPrice(num, options = {}) {
  2. const showSymbol = options.showSymbol !== false;
  3. const showDecimals = options.showDecimals !== false;
  4. return num.toLocaleString('en', {
  5. style: showSymbol ? 'currency' : undefined,
  6. currency: showSymbol ? 'USD' : undefined,
  7. maximumFractionDigits: showDecimals ? 2 : 0
  8. });
  9. }
  10. const Page = () => {
  11. const lambPrice = 1234.567;
  12. const jetPrice = 999999.99;
  13. const bootPrice = 34.567;
  14. return (
  15. <div>
  16. <p>One lamb is <span className="expensive">{numberToPrice(lambPrice)}</span></p>
  17. <p>One jet is {numberToPrice(jetPrice, { showDecimals: false })}</p>
  18. <p>Those gumboots will set ya back
  19. {numberToPrice(bootPrice, { showDecimals: false, showSymbol: false })}
  20. bucks.</p>
  21. </div>
  22. );
  23. };

参考资料: