我试图将流程实施到我的React应用程序中。到目前为止它工作正常,但我遇到了默认值的问题。
函数头是:
const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
TFormControls的类型别名是:
type TFormControls = {
onSubmit?: boolean,
onReset?: boolean,
onClear?: boolean
}
我希望,因为我在那里放了一个可能的运算符controls: ?TFormControls
,它可能是我的类型别名或null / undefined,但是流程告诉我:
src/components/forms/FormControls.jsx:35
35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
^^^^^^^^ null. This type is incompatible with
35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
^^^^^^^^ object type
src/components/forms/FormControls.jsx:35
35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
^^^^^^^^ object type. This type is incompatible with
35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
^^^^^^^^ null
任何指针都是最受欢迎的!
编辑:根据要求,包含错误的完整功能example
答案 0 :(得分:3)
您正在寻找的是defaultProps class property。
特别是,您可以在此处定义道具参数:
type FormControlsPropsType = {
form: Object,
controls: TFormControls,
labels: TFormControlLabels
};
const FormControls = ({
form,
controls,
labels
} : FormControlsPropsType): React.Element<*> => (
// ...etc
);
以下是定义defaultProps的方法:
FormControls.defaultProps = {
controls: null,
labels: {},
}
最后,因为您正在定义默认值,所以没有理由使用可选参数定义PropsType。你会看到我删除了?
。
通过在参数定义中设置默认值,您可能与React$Element内部发生冲突。