用来做format的组件
在我们需要格式化字符串的时候, 我们可以在render方法中去使用helper函数. 然而, 更好的方法是去使用一个组件去做这件事.
使用组件的做法
render函数的实现会更加的干净因为只会是一些组件的组合.
const Price = (props) => {
// toLocaleString 并不是React的API而是原生JavaScript的内置方法
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
const price = props.children.toLocaleString('en', {
style: props.showSymbol ? 'currency' : undefined,
currency: props.showSymbol ? 'USD' : undefined,
maximumFractionDigits: props.showDecimals ? 2 : 0
});
return <span className={props.className}>{price}</span>
};
Price.propTypes = {
className: PropTypes.string,
children: PropTypes.number,
showDecimals: PropTypes.bool,
showSymbol: PropTypes.bool
};
Price.defaultProps = {
children: 0,
showDecimals: true,
showSymbol: true,
};
const Page = () => {
const lambPrice = 1234.567;
const jetPrice = 999999.99;
const bootPrice = 34.567;
return (
<div>
<p>One lamb is <Price className="expensive">{lambPrice}</Price></p>
<p>One jet is <Price showDecimals={false}>{jetPrice}</Price></p>
<p>Those gumboots will set ya back
<Price
showDecimals={false}
showSymbol={false}>
{bootPrice}
</Price>
bucks.
</p>
</div>
);
};
不使用组件的做法.
代码量更少, 但是让render方法看起来不那么干净(作者个人感觉, 哈哈)
function numberToPrice(num, options = {}) {
const showSymbol = options.showSymbol !== false;
const showDecimals = options.showDecimals !== false;
return num.toLocaleString('en', {
style: showSymbol ? 'currency' : undefined,
currency: showSymbol ? 'USD' : undefined,
maximumFractionDigits: showDecimals ? 2 : 0
});
}
const Page = () => {
const lambPrice = 1234.567;
const jetPrice = 999999.99;
const bootPrice = 34.567;
return (
<div>
<p>One lamb is <span className="expensive">{numberToPrice(lambPrice)}</span></p>
<p>One jet is {numberToPrice(jetPrice, { showDecimals: false })}</p>
<p>Those gumboots will set ya back
{numberToPrice(bootPrice, { showDecimals: false, showSymbol: false })}
bucks.</p>
</div>
);
};