问题描述
我正在尝试从反应.
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>
.
I believe that I need to map
over the productRows
, i.e. List of ProductRow
's, with a function of: productRow => <td>productRow</td>
.
在此示例中,我该怎么做?
How can I do that in this example?
或者,如果我完全没有能力,请说明如何实现上述目标.
Or, if I'm completely off the mark, please explain how I can achieve the above.
推荐答案
在"Thinking in React"页面中,组件嵌套层次结构使得ProductTable
包含多个ProductRow
.通过在一系列产品上进行映射并生成ProductRow
作为输出,我们可以在ReasonReact中对该模型进行建模.例如:
In the 'Thinking in React' page, the component nesting hierarchy is such that a ProductTable
contains several ProductRow
s. We can model that in ReasonReact by mapping over an array of products and producing ProductRow
s as the output. E.g.:
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");
这篇关于将React组件传递给另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!