ReasonReact-Todo-Tutorial-PartIII

Rendering items

希望有一個區塊 Component 來顯示輸入的 items

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
type item = {
title: string,
completed: bool
};

module TodoItem = {
let component = ReasonReact.statelessComponent("TodoItem");
let make = (~item, _children) => {
...component,
render: (_self) =>
<div className="item">
<input
_type="checkbox"
checked=(item.completed)
/* TODO make interactive */
/>
(ReasonReact.string(item.title))
</div>
};
};

type state = {items: list(item)};

type action =
| AddItem;

let component = ReasonReact.reducerComponent("TodoApp");

let newItem = () => {title: "Click a button", completed: true};

let make = (_children) => {
...component,
initialState: () => {
items: [
{title: "Write some things to do", completed: false}
]
},
reducer: (action, {items}) =>
switch action {
| AddItem => ReasonReact.Update({items: [newItem(), ...items]})
},
render: (self) => {
let numItems = List.length(self.state.items);
<div className="app">
<div className="title">
(ReasonReact.string("What to do"))
<button onClick=(_event => self.send(AddItem))>
(ReasonReact.string("Add something"))
</button>
</div>
<div className="items">
(
ReasonReact.array(Array.of_list(
List.map((item) => <TodoItem item />, self.state.items)
))
)
</div>
<div className="items"> (ReasonReact.string("Nothing")) </div>
<div className="footer">
(ReasonReact.string(string_of_int(numItems) ++ " items"))
</div>
</div>
}
};

我們又增加了一些東西

和一般的 JSX 有一點不一樣 <TodoItem item />

他原本也是 <TodoItem item=item /> 的簡寫

JSX 中則會被解釋為 <TodoItem item={true} />

1
2
3
ReasonReact.array(Array.of_list(
List.map((item) => <TodoItem item />, self.state.items)
))

可以看到這個寫法

但是其實也可以改成

1
self.state.items |> List.map((item) => <TodoItem item />) |> Array.of_list |> ReasonReact.array
文章目录
  1. 1. Rendering items
|