3

我正在学习reasonml,对此非常兴奋。我在打字稿反应代码中经常做的事情是:

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 元素组件结合起来。

有什么建议吗?谢谢!

4

1 回答 1

2

ReasonReact.cloneElement正如 Amirali 暗示的那样,可以使用 来做类似的事情。想法是将组件的 props 和 HTML 按钮的 props 拆分为组件的两个单独参数,渲染按钮,然后克隆它,同时注入额外的按钮 props。

此页面显示了一个封装此克隆和注入功能的组件:

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>;
};

htmlButtonProps道具将包含常规 HTML 按钮道具,而单独foo是您的组件的特定道具。该组件可以这样使用:

<SuperButton foo=true htmlButtonProps={"autofocus": true} />

小管家注意:您实际上不需要使用module关键字定义模块。如果您愿意,可以将它们放在名为Spread.reand的单独文件中SuperButton.re。原因文件自动成为模块。

于 2020-07-12T16:06:07.823 回答