在 ReasonReact 中处理 children

Handling children in ReasonReact

我正在尝试构建自己的 <MySelect> 组件,用户可以在其中传递自己的 <option>。像这样:

<MySelect label="Pick a color" onChange={...}>
    <option value="blue">(ReasonReact.string("Blue"))</option>
    <option value="red">(ReasonReact.string("Red"))</option>
    <option value="green">(ReasonReact.string("Green"))</option>
</MySelect>

但是我不明白如何处理 MySelect 中的 childrenThe docs (and here) 未显示完整示例。

尝试

/* ... */
make = (~label, ~onChange, children) =>
    <label>
        <div>(ReasonReact.string(label))</div>
        <select onChange=onChange>
            ...children
        </select>
    </label>

我明白了

Error: function call with [@@bs.val "createElement"]  is a primitive with [@bs.splice], it expects its `bs.splice` argument to be a syntactic array in the call site and  all arguments to be supplied

没有传播(所以 children 而不是 ...children)我得到

Did you pass an array as a ReasonReact DOM (lower-case) component's children?
If not, disregard this. If so, please use `ReasonReact.createDomElement`:
https://reasonml.github.io/reason-react/docs/en/children.html

Here's the original error message
This has type:
  array('a)
But somewhere wanted:
  ReasonReact.reactElement

我确信这些错误消息与文档结合起来告诉了我所有我需要知道的;生词太多,看不懂。

我也尝试过 google 作为示例(这看起来是一个相当正常的用例),但在我发现的任何地方,他们都完全忽略了 children。

select 是一个 DOM(小写)组件,因此您需要使用 createDomElement。文档中的相关部分位于:https://reasonml.github.io/reason-react/docs/en/children.html#pitfall。用一个例子稍微修改一下你的例子:

module MySelect = {
  let component = ReasonReact.statelessComponent("MySelect");

  let make = (~label, ~onChange, children) => {
    ...component,
    render: _ =>
      <label>
        <div> (ReasonReact.string(label)) </div>
        (
          ReasonReact.createDomElement(
            "select",
            ~props={"onChange": onChange},
            children,
          )
        )
      </label>,
  };
};

module Example = {
  let component = ReasonReact.statelessComponent("Example");

  let make = _children => {
    ...component,
    render: _ =>
      <MySelect label="test" onChange=(value => Js.log(value))>
        <option value="blue"> (ReasonReact.string("Blue")) </option>
        <option value="red"> (ReasonReact.string("Red")) </option>
        <option value="green"> (ReasonReact.string("Green")) </option>
      </MySelect>,
  };
};