通过父子组件之间通信,使用 props
从父组件把数据传递到子组件中。
在 App 组件中通过 state
定义 TodoList 数据列表,代码片段如下:
// src/App.jsstate = {todoList: [{ id: 1, name: "参加晨会", done: true },{ id: 2, name: "A功能开发", done: true },{ id: 3, name: "B功能开发", done: false },],
};
通过 props
将 state
中的 TodoList 数据传递到 List 组件中,代码片段如下:
// src/App.jstodoList} />
在 List 组件中接收通过 props
传递进来的数据,并渲染到到组件中,代码片段如下:
// src/components/List/index.jsx// 修改 List 组件的 render() 函数如下
render() {// 从 props 读取 TodoListconst { todoList } = this.props;return ({/* 遍历渲染 Item 组件,同时将 TodoList 的数据传入 */}{todoList.map((todo) => {return - todo.id} {...todo} />;})}
);
}
代码技巧:
这个代码中使用了 js 的展开运算符
...
可以高效灵活的将一个对象展开为组件的props
属性。
在 Item 组件中接收通过 props
传递进来的数据,并渲染到到组件中,代码片段如下:
// src/components/Item/index.jsx// 修改 Item 组件的 render() 函数如下
render() {// 从 props 读取 TodoList 的数据const { name, done } = this.props;return ();
}
注意:
中初始渲染 TodoList 记录的初始状态,要使用
defaultChecked
,而不能使用checked
,如果使用了checked
则会导致界面上的 checkbox 点击时不能切换选中/取消的状态了。
至此,完成了 TodoList 列表的数据动态化。
// file: src/App.jsimport 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 (todoList} />
);}
}
// file: src/components/List/index.jsximport React, { Component } from "react";
import Item from "../Item";
import "./index.css";export default class List extends Component {render() {// 从 props 读取 TodoListconst { todoList } = this.props;return ({/* 遍历渲染 Item 组件,同时将 TodoList 的数据传入 */}{todoList.map((todo) => {return - todo.id} {...todo} />;})}
);}
}
// file: src/components/Item/index.jsximport React, { Component } from "react";
import "./index.css";export default class Item extends Component {render() {const { name, done } = this.props;return ();}
}
至此完成 TodoList 组件列表动态初始化。
下一篇:笔试强训48天——day24