我是ReasonML的新手.我能够使用ReasonReact成功创建无状态组件,但我还没弄清楚如何向组件添加自定义方法(例如 Next.js’ static getInitialProps ). 当试图在组件上定义getInitialProps方法时,我收到一
getInitialProps).
当试图在组件上定义getInitialProps方法时,我收到一个字段getInitialProps不属于ReasonReact.componentSpec类型错误.
我应该如何在React组件上添加此自定义方法?
零件
let str = ReasonReact.stringToElement;
let component = ReasonReact.statelessComponent("Index");
let make = (~items: Listings.items, _children) => {
...component,
getInitialProps: () =>
Js.Promise.(
Endpoints.fetchListings()
|> then_(Fetch.Response.json)
|> then_((json) => Js.Json.decodeArray(json) |> resolve)
),
render: (_self) =>
<div>
(List.length(items) > 0 ? <Listings items /> : <Loading />)
</div>
};
let default =
ReasonReact.wrapReasonForJs(
~component,
(jsProps) => make(~items=jsProps##items, [||])
);
错误
We've found a bug for you!
/Users/davidcalhoun/Sites/web/evergreen-roots/pages/Index.re 7:3-17
5 │ let make = (~items: Listings.items, _children) => {
6 │ ...component,
7 │ getInitialProps: () =>
8 │ Js.Promise.(
9 │ Endpoints.fetchListings()
This record expression is expected to have type
ReasonReact.componentSpec ('a, 'b, 'c, 'd, 'e)
The field getInitialProps does not belong to type ReasonReact.componentSpec
在Discord中回答,重新发布在这里:
您无法在组件上定义任意方法.看到……组件?这是用静态字段传播记录并像你一样更新一些字段,例如渲染.
另外,我相信你不能直接将ReasonReact组件传递给下一个方法.它可能要求反应组件类.请参阅interop section,了解如何为js端公开底层的js类.
在此期间,您可以将该组件包装在定义getInitialProps的js组件的薄层中
所以你有一个带有getInitialProps的reactjs组件,它呈现一个通过interop公开底层类的ReasonReact组件.
如果我正确理解你,如果你正在使用Reason的那个包装器,那么你也可以将ReasonReact绑定写入该js包装器.这使得这个过程有点人为,但你在这里遇到一个病态的案例.
作为一个方面:理想情况下,Next.js API会要求一个组件类,另一个是getInitialProps,这是一个完全不可知的函数,它没有附加到组件类上.这大大简化了Reason方面的绑定过程.
