官术网_书友最值得收藏!

Adding state to our screen

Let's add some initial state to our ShoppingList screen to populate the list with actual dynamic data. We will start by creating a constructor and setting the initial state there:

/*** ShoppingList.js ***/

...
constructor(props) {
super(props);
this.state = {
products: [{ id: 1, name: 'bread' }, { id: 2, name: 'eggs' }]
};
}
...

Now, we can render that state inside of <List> (inside the render method):

/*** ShoppingList.js ***/

...
<List>
{
this.state.products.map(p => {
return (
<ListItem
key={p.id}
>
<Body>
<Text style={{ color: p.gotten ? '#bbb' : '#000' }}>
{p.name}
</Text>
</Body>
<Right>
<CheckBox
checked={p.gotten}
/>
</Right>
</ListItem>
);
}
)}
</List>
...

We now rely on a list of products inside our component's state, each product storing an id, a name, and gotten properties. When modifying this state, we will automatically be re-rendering the list.

Now, it's time to add some event handlers, so we can modify the state at the users' command or navigate to the AddProduct screen.

主站蜘蛛池模板: 额尔古纳市| 乌海市| 民县| 宝应县| 洪湖市| 利辛县| 吉安市| 方山县| 加查县| 高青县| 友谊县| 家居| 永顺县| 集贤县| 临湘市| 旬阳县| 缙云县| 会理县| 正镶白旗| 和硕县| 海安县| 南充市| 鄂温| 海林市| 西宁市| 高平市| 吉水县| 绥宁县| 马鞍山市| 共和县| 白朗县| 绥德县| 夏河县| 中西区| 长顺县| 双桥区| 衡阳市| 阳谷县| 安远县| 裕民县| 望谟县|