我正在学习reasonml,并对此感到非常兴奋。我在typescript react代码中经常做的事情是:
type Props = React.HTMLProps<HTMLButtonElement> & { foo: boolean }
const SuperButton: React.FC<Props> = (props) => <button {/* stuff with props */ />在这方面,我以组件库提供商的身份告诉我的用户,这个按钮扩展了普通的HTML按钮属性。
如何在我的组件中表达和扩展普通的html组件属性?
我明白这个原因显然不支持传播道具:https://github.com/reasonml/reason-react/blob/master/docs/props-spread.md。
我确实看到有一种组合策略:How to compose props across component in reason-react bindings?,但不确定如何将其与普通的HTML元素组件结合起来。
有什么建议吗?谢谢!
发布于 2020-07-13 00:06:08
正如阿米拉利所暗示的那样,使用ReasonReact.cloneElement也可以做类似的事情。这个想法是将组件的道具和HTML按钮的道具分成组件的两个单独的参数,呈现按钮,然后克隆它,同时注入额外的按钮道具。
This page显示了一个组件,它封装了这种克隆和注入功能:
module Spread = {
[@react.component]
let make = (~props, ~children) =>
ReasonReact.cloneElement(children, ~props, [||]);
};现在,您可以将此Spread组件用于您的SuperButton组件:
module SuperButton = {
[@react.component]
let make = (~foo, ~htmlButtonProps) =>
<Spread props=htmlButtonProps>
<button> (foo ? "YES" : "NO")->React.string </button>
</Spread>;
};HTML将包含常规的htmlButtonProps按钮prop,而单独的foo则是组件的特定prop。该组件的使用方法如下:
<SuperButton foo=true htmlButtonProps={"autofocus": true} />注意事项:您实际上不需要使用module关键字来定义模块。如果需要,您可以将它们放在名为Spread.re和SuperButton.re的单独文件中。原因文件自动成为模块。
https://stackoverflow.com/questions/62854705
复制相似问题