在ReasonReact中处理孩子

时间:2018-07-24 14:36:28

标签: reason reason-react

我正在尝试构建自己的<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>

但是我不知道如何处理children中的MySelectThe docsand 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

我确信这些错误信息和文档都可以告诉我所有我需要知道的信息;对于我来说,有太多未知的单词使我无法理解。

我也曾尝试用谷歌搜索示例(这似乎是一个很正常的用例),但是在我发现的所有地方,他们都完全忽略了孩子。

1 个答案:

答案 0 :(得分:1)

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