原因组件

时间:2018-02-14 03:50:37

标签: reason reason-react

借用Yawar的所有帮助answer,我有以下内容:

$cat src/index.re 
let products = [|
  {name: "Football", price: 49.99},
  {name: "Basebll", price: 1.99},
  {name: "Poker", price: 33.99}
|];

ReactDOMRe.renderToElementWithId(
    <ProductTable products />
);

$cat src/productRow.re
let component = ReasonReact.statelessComponent("ProductRow");

let echo = ReasonReact.stringToElement;

let make = (~name: string, ~price: float, _) => {
 ...component,
 render: (_) => {
    <tr>
     <td>{echo(name)}</td>
     <td>{price |> string_of_float |> echo}</td>
    </tr>
 }
};
$cat src/ProductTable.re
let component = ReasonReact.statelessComponent("ProductTable");

let echo = ReasonReact.stringToElement;

let make = (~products, _) => {
    ...component,
    render: (_) => {
      let productRows = products
        |> Array.map(({name, price}) => <ProductRow key=name name price />)
        |> ReasonReact.arrayToElement;

      <table>
        <thead>
          <tr>
            <th>{echo("Name")}</th>
            <th>{echo("Price")}</th>
          </tr>
        </thead>
        <tbody>productRows</tbody>
      </table>
    }
}

我收到以下编译时错误:

   7 ┆ render: (_) => {
   8 ┆   let productRows = products
   9 ┆     |> Array.map(({name, price}) => <ProductRow key=name name price />
       )
  10 ┆     |> ReasonReact.arrayToElement;
  11 ┆ 

  Unbound record field name

如何修复此编译时错误?

1 个答案:

答案 0 :(得分:3)

Reason编译器会为你推断出很多类型,但是对于记录,你必须首先声明它具有哪些字段(及其类型)。

从@ yawar的有用答案中提取,您只需要在文件顶部包含类型定义:

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

通过这种方式,编译器将能够告诉products类型为array(product),并且应该从那里继续愉快地继续。试一试here