我想将事件处理程序从父级传递给子级的一系列组件。这是一个工作示例:
索引.re
ReactDOMRe.renderToElementWithId(
<App myHandler={_evt => Js.log("my handler clicked")} />,
"root",
);
应用程序
let component = ReasonReact.statelessComponent(__MODULE__);
let make = (~myHandler, _children) => {
...component,
render: _self => <MyComponent myHandler />,
};
我的组件
let component = ReasonReact.statelessComponent(__MODULE__);
let make = (~myHandler, _children) => {
...component,
render: _self =>
<div onClick=myHandler> {ReasonReact.string("click me")} </div>,
}
就像现在的代码一样myHandler
,每个组件使用时都需要参数,否则我们会收到错误:
This call is missing an argument of type (~myHandler: ReactEvent.Mouse.t => unit)
=?
通过在函数声明中添加 a 可以使带标签的参数成为可选的,如下所示:
let component = ReasonReact.statelessComponent(__MODULE__);
let make = (~myHandler=?, _children) => {
...component,
render: _self =>
<div onClick=myHandler> {ReasonReact.string("click me")} </div>,
};
但是,这会产生编译错误:
5 │ ...component,
6 │ render: _self =>
7 │ <div onClick=myHandler> {ReasonReact.string("click me")} </div>,
8 │ };
This has type:
option('a)
But somewhere wanted:
ReactEvent.Mouse.t => unit
我想也许编译器可能需要一个提示。因此,我尝试将该类型显式添加到函数声明中,如下所示:
let component = ReasonReact.statelessComponent(__MODULE__);
let make = (~myHandler: ReactEvent.Mouse.t => unit=?, _children) => {
...component,
render: _self =>
<div onClick=myHandler> {ReasonReact.string("click me")} </div>,
};
但随后错误转向我并给了我:
4 │ let make = (~myHandler: ReactEvent.Mouse.t => unit=?, _children) => {
5 │ ...component,
6 │ render: _self =>
This pattern matches values of type
ReactEvent.Mouse.t => unit
but a pattern was expected which matches values of type
option('a)
现在我很困惑。