1

我正在尝试定义一个ProductRowand ProductCategoryRowfrom Thinking in React

productRow.re

let component = ReasonReact.statelessComponent("ProductRow");

let make = (~name, ~price, _children) => {
  ...component,
  render: (_self) => {
    <tr>
      <td>{ReasonReact.stringToElement(name)}</td>
      <td>{ReasonReact.stringToElement(price)}</td>
    </tr>
  }
};

productCategoryRow.re

let component = ReasonReact.statelessComponent("ProductCategoryRow");

let make = (~title: string, ~productRows, _children) => {
  ...component,
  render: (_self) => {
    <div>
        <th>{ReasonReact.stringToElement(title)}</th>
    </div>
  }
};

我相信我需要map通过productRows,即List of ProductRow,具有以下功能:productRow => <td>productRow</td>

在这个例子中我该怎么做?

或者,如果我完全不合时宜,请解释我如何实现上述目标。

4

1 回答 1

2

在“Thinking in React”页面中,组件嵌套层次结构使得 aProductTable包含多个ProductRows。我们可以在 ReasonReact 中通过映射一个产品数组并生成ProductRows 作为输出来对其进行建模。例如:

type product = {name: string, price: float};

/* Purely for convenience */
let echo = ReasonReact.stringToElement;

module ProductRow = {
  let component = ReasonReact.statelessComponent("ProductRow");
  let make(~name, ~price, _) = {
    ...component,
    render: (_) => <tr>
      <td>{echo(name)}</td>
      <td>{price |> string_of_float |> echo}</td>
    </tr>
  };
};

module ProductTable = {
  let component = ReasonReact.statelessComponent("ProductTable");
  let make(~products, _) = {
    ...component,
    render: (_) => {
      let productRows = products
        /* Create a <ProductRow> from each input product in the array. */
        |> Array.map(({name, price}) => <ProductRow key=name name price />)
        /* Convert an array of elements into an element. */
        |> ReasonReact.arrayToElement;

      <table>
        <thead>
          <tr> <th>{echo("Name")}</th> <th>{echo("Price")}</th> </tr>
        </thead>
        /* JSX can happily accept an element created from an array */
        <tbody>productRows</tbody>
      </table>
    }
  };
};

/* The input products. */
let products = [|
  {name: "Football", price: 49.99},
  {name: "Baseball", price: 9.99},
  {name: "Basketball", price: 29.99}
|];

ReactDOMRe.renderToElementWithId(<ProductTable products />, "index");
于 2018-01-30T05:00:49.670 回答