- 样式函数(Style Functions)
- 第一个例子
- 第二个例子
样式函数(Style Functions)
因为在React中可以很方便的使用JavaScript, 所以我们能使用helper函数来帮我们处理样式相关的问题.
第一个例子
一个用rgba格式来创造黑色的函数.
const darken = (n) => `rgba(0, 0, 0, ${n})`;darken(1 / 8); // 'rgba(0, 0, 0, 0.125)'const shade = [darken(0),darken(1 / 8),darken(1 / 4),darken(3 / 8),darken(1 / 2),darken(5 / 8),darken(3 / 4),darken(7 / 8),darken(1)];// 现在,// shade[4] 就是 'rgba(0, 0, 0, 0.5)'
第二个例子
给margin 和 padding创建一个比例来保持视觉节奏的一致.
// Modular powers of two scaleconst scale = [0,8,16,32,64];// 通过这个函数去取得一部分的样式const createScaledPropertyGetter = (scale) => (prop) => (x) => {return (typeof x === 'number' && typeof scale[x] === 'number')? {[prop]: scale[x]}: null};const getScaledProperty = createScaledPropertyGetter(scale);export const getMargin = getScaledProperty('margin');export const getPadding = getScaledProperty('padding');// 样式函数的用法const Box = ({m,p,...props}) => {const sx = {...getMargin(m),...getPadding(p)};return <div {...props} style={sx}/>};// 组件用法.const Box = () => (<div><Box m={2} p={3}>A box with 16px margin and 32px padding</Box></div>);
