定义理由反应绑定时,我想知道如何确定接受多种类型的绑定.例如,我有一个应该接受的参数〜值:字符串,数字,数组(字符串)或数组(数字).目前我正在使用选项(‘a),但我不认为这是最干
module Select = {
[@bs.module "material-ui/Select"] external reactClass : ReasonReact.reactClass = "default";
let make =
(
...
~menuProps: option(Js.t({..}))=?,
~value: option('a), /* Should be type to string, number, Array of string and Array of number */
~style: option(ReactDOMRe.style)=?,
...
children
) =>
ReasonReact.wrapJsForReason(
~reactClass,
~props=
Js.Nullable.(
{
...
"value": from_opt(value),
"style": from_opt(style)
}
),
children
);
};
作为一个附带问题,由于数字类型没有在原因中定义,我的绑定还必须将float和integer映射到数字?
这可以通过使用以下(灵感来自 https://github.com/astrada/reason-react-toolbox/)来实现.type jsUnsafe;
external toJsUnsafe : 'a => jsUnsafe = "%identity";
let unwrapValue =
(r: [< | `Int(int) | `IntArray(array(int)) | `String(string) | `StringArray(array(string))]) =>
switch r {
| `String(s) => toJsUnsafe(s)
| `Int(i) => toJsUnsafe(i)
| `StringArray(a) => toJsUnsafe(a)
| `IntArray(a) => toJsUnsafe(a)
};
let optionMap = (fn, option) =>
switch option {
| Some(value) => Some(fn(value))
| None => None
};
module Select = {
[@bs.module "material-ui/Select"] external reactClass : ReasonReact.reactClass = "default";
let make =
(
...
~menuProps: option(Js.t({..}))=?,
~value:
option(
[ | `Int(int) | `IntArray(array(int)) | `String(string) | `StringArray(array(string))]
)=?,
~style: option(ReactDOMRe.style)=?,
...
children
) =>
ReasonReact.wrapJsForReason(
~reactClass,
~props=
Js.Nullable.(
{
...
"value": from_opt(optionMap(unwrapValue, value)),
"style": from_opt(style)
}
),
children
);
};
这可以通过以下方式使用;
<Select value=(`IntArray([|10, 20|])) /> <Select value=(`Int(10)) />
我从reason-react-toolbox复制到了JSUnsafe,所以我不完全确定它的作用,当我发现时我会更新我的答案.
unwrapValue函数接受一个值,该值可以是列出的类型之一,并将其转换为jsUnsafe.
unwrapValue的类型允许列出的任何变体,但也允许其中的一部分,例如. (这是<在启用此功能的变体之前).
let option = (value: option([ | `String(string) | `Int(int)])) => Js.Nullable.from_opt(option_map(unwrapValue, value));
