文章目录
本文实现 TodoList 组件列表动态初始化。
目标实现效果
实现思路
通过父子组件之间通信,使用 props
从父组件把数据传递到子组件中。
实现步骤
第一步:App 组件定义 TodoList 动态数据列表
在 App 组件中通过 state
定义 TodoList 数据列表,代码片段如下:
// src/App.js
state = {
todoList: [
{ id: 1, name: "参加晨会", done: true },
{ id: 2, name: "A功能开发", done: true },
{ id: 3, name: "B功能开发", done: false },
],
};
第二步:App 组件通过 props 传递数据到子组件 List
通过 props
将 state
中的 TodoList 数据传递到 List 组件中,代码片段如下:
// src/App.js
<List todoList={todoList} />
第三步:List 组件接收 props 传入数据,并传入子组件 Item
在 List 组件中接收通过 props
传递进来的数据,并渲染到到组件中,代码片段如下:
// src/components/List/index.jsx
// 修改 List 组件的 render() 函数如下
render() {
// 从 props 读取 TodoList
const { todoList } = this.props;
return (
<ul className="todo-main">
{/* 遍历渲染 Item 组件,同时将 TodoList 的数据传入 */}
{todoList.map((todo) => {
return <Item key={todo.id} {...todo} />;
})}
</ul>
);
}
代码技巧:
<Item key={todo.id} {...todo} />
这个代码中使用了 js 的展开运算符...
可以高效灵活的将一个对象展开为组件的props
属性。
第四步:Item 组件接收 props 数据
在 Item 组件中接收通过 props
传递进来的数据,并渲染到到组件中,代码片段如下:
// src/components/Item/index.jsx
// 修改 Item 组件的 render() 函数如下
render() {
// 从 props 读取 TodoList 的数据
const { name, done } = this.props;
return (
<li>
<label className="container">
<input type="checkbox" defaultChecked={done} />
<span>{name}</span>
</label>
<button className="btn btn-danger btn-sm" style={{ display: "none" }}>
删除
</button>
</li>
);
}
注意:
<input type="checkbox" defaultChecked={done} />
中初始渲染 TodoList 记录的初始状态,要使用defaultChecked
,而不能使用checked
,如果使用了checked
则会导致界面上的 checkbox 点击时不能切换选中/取消的状态了。
至此,完成了 TodoList 列表的数据动态化。
完整代码
App 组件完整代码
// file: src/App.js
import React, { Component } from "react";
import Header from "./components/Header";
import List from "./components/List";
import Footer from "./components/Footer";
import "./App.css";
export default class App extends Component {
// 初始化状态
state = {
todoList: [
{ id: 1, name: "参加晨会", done: true },
{ id: 2, name: "A功能开发", done: true },
{ id: 3, name: "B功能开发", done: false },
],
};
render() {
const { todoList } = this.state;
return (
<div className="todo-container">
<div className="todo-wrap">
<Header />
<List todoList={todoList} />
<Footer />
</div>
</div>
);
}
}
List 组件完整代码
// file: src/components/List/index.jsx
import React, { Component } from "react";
import Item from "../Item";
import "./index.css";
export default class List extends Component {
render() {
// 从 props 读取 TodoList
const { todoList } = this.props;
return (
<ul className="todo-main">
{/* 遍历渲染 Item 组件,同时将 TodoList 的数据传入 */}
{todoList.map((todo) => {
return <Item key={todo.id} {...todo} />;
})}
</ul>
);
}
}
Item 组件完整代码
// file: src/components/Item/index.jsx
import React, { Component } from "react";
import "./index.css";
export default class Item extends Component {
render() {
const { name, done } = this.props;
return (
<li>
<label className="container">
<input type="checkbox" defaultChecked={done} />
<span>{name}</span>
</label>
<button className="btn btn-danger btn-sm" style={{ display: "none" }}>
删除
</button>
</li>
);
}
}
至此完成 TodoList 组件列表动态初始化。