gpt4 book ai didi

reason - 设计reasonml react组件时如何扩展HTML属性接口(interface)?

转载 作者:行者123 更新时间:2023-12-04 15:23:14 25 4
gpt4 key购买 nike

我正在学习 reasonml 并且对此感到非常兴奋。我在 typescript react 代码中经常做的事情是:

type Props = React.HTMLProps<HTMLButtonElement> & { foo: boolean }
const SuperButton: React.FC<Props> = (props) => <button {/* stuff with props */ />

在这方面,我作为组件库提供者向我的用户传达这个按钮扩展了普通的 HTML 按钮属性。

如何在我的组件中表达和扩展普通的 html 组件属性?

我看到 reason 明确不支持传播 props:https://github.com/reasonml/reason-react/blob/master/docs/props-spread.md .

我确实看到有一个组合策略:How to compose props across component in reason-react bindings? ,但不确定如何将它与普通的 HTML 元素组件结合起来。

有什么建议吗?谢谢!

最佳答案

正如 Amirali 暗示的那样,使用 ReasonReact.cloneElement 可以做类似的事情。这个想法是将组件的 Prop 和 HTML 按钮的 Prop 分成两个单独的组件参数,呈现按钮,然后克隆它,同时注入(inject)额外的按钮 Prop 。

This page显示了封装此克隆和注入(inject)功能的组件:

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.reSuperButton.re 的单独文件中。原因文件自动成为模块。

关于reason - 设计reasonml react组件时如何扩展HTML属性接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62854705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com