我有一个名为样式的模块。
export default (props = {}) => ({
tile: {
width: props.width,
listStyle: "none"
},
banner: {
color: 'red',
}
})
如果我 import styles from './styles.js;
我基本上希望能够做两件事:
像这样获取 tile 样式:styles({width:}).tile
并获得像这样的横幅样式:styles.banner
,所以不要像 styles().banner
那样调用它。
如何做到这一点?
编辑:很抱歉,没能把我的问题说清楚。 定义 的对象应始终具有如下结构:
tile: {
width: props.width,
listStyle: "none"
},
banner: {
color: 'red',
}
返回这个对象的函数可以看成任何你想要的。
最佳答案
我不知道您为什么要这样做,但您可以执行以下操作。需要区分哪些样式可以不带参数返回(“independentStyles”),哪些需要输入值:
const independentStyles = {
banner: {
color: 'red',
},
};
const styles = (props = {}) => Object.assign({}, independentStyles, {
tile: {
width: props.width,
listStyle: "none"
},
});
// put the properties on the function object
Object.assign(styles, independentStyles);
console.log(styles({ width: 30 }).tile); // { width: 30, listStyle: 'none' }
console.log(styles().tile); // { width: undefined, listStyle: 'none' }
console.log(styles().banner); // { color: 'red' }
console.log(styles.banner); // { color: 'red' }
console.log(styles.tile); // undefined - can't be determined without props
// export default styles;
关于javascript - 如何制作可选调用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50333056/