const propsDefault = {
open: false,
payload: {
title: '默认提交',
styles: stylesDefault,
data: '默认显示内容',
onSubmit: null,
diableSubmit: false,
onCancel: null,
diableCancel: false,
},
};
function defaultProps(payload) {
const formatedProps = {};
if (payload.onSubmit === undefined) { formatedProps.onSubmit = propsDefault.payload.onSubmit; } else { formatedProps.onSubmit = payload.onSubmit; }
if (payload.diableSubmit === undefined) { formatedProps.diableSubmit = propsDefault.payload.diableSubmit; } else { formatedProps.diableSubmit = payload.diableSubmit; }
if (payload.onCancel === undefined) { formatedProps.onCancel = propsDefault.payload.onCancel; } else { formatedProps.onCancel = payload.onCancel; }
if (payload.diableCancel === undefined) { formatedProps.diableCancel = propsDefault.payload.diableCancel; } else { formatedProps.diableCancel = payload.diableCancel; }
if (payload.title === undefined) { formatedProps.title = propsDefault.payload.title; } else { formatedProps.title = payload.title; }
if (payload.styles === undefined) { formatedProps.styles = propsDefault.payload.styles; } else { formatedProps.styles = payload.styles; }
if (payload.data === undefined) { formatedProps.data = propsDefault.payload.data; } else { formatedProps.data = payload.data; }
return formatedProps;
}
这写法太难看了 ES6 有什么好看的写法?
1
ZIrong 2018-04-03 20:10:17 +08:00
```
const defaultProps = (payload) => { const formatedProps = {}; formatedProps.onSubmit = payload.onSubmit || propsDefault.payload.onSubmit } ``` |
2
brickyang 2018-04-03 20:14:44 +08:00 via iPhone
|
3
brickyang 2018-04-03 20:19:58 +08:00 via iPhone 3
具体楼主这个场景,更适合 Object.assign({}, ...defaultProps, payload)
这个方法,payload 里如果有对应的属性,即使是 null 或空值也会覆盖到新对象中。 短路赋值的问题是,如果 payload 中存在的属性是 null 或空值,都会使用 default 中的值。 |
4
lolizeppelin OP 谢谢 3 楼 就是这个
|
5
lolizeppelin OP 3 楼的方式不行 orz 丢属性 1 楼的可以 orz
|
6
lrz0lrz 2018-04-03 23:26:37 +08:00
|
7
lrz0lrz 2018-04-03 23:35:38 +08:00
呃,理解错误,抱歉
{...defaultProps, ...propsDefault.payload} 这样就行了 |
8
lolizeppelin OP 握草 楼上这个方法好
|
9
sunnygaofan 2018-04-03 23:43:43 +08:00 via iPhone
@brickyang 谢谢,纠结这个问题很久了
|