父组件 -> 子组件:通过 props 传递 子组件 -> 父组件:通过 props 传递,但是父组件需要提取给子组件传递一个预定义的函数
父组件 父组件将定义好的数据直接用直接通过 props 传递
import React, { Component } from "react";
import List from "./component/List";
export default class App extends Component {
// 初始化状态
state = {
todos: [
{ id: "1", name: "吃饭", done: true },
{ id: "2", name: "睡觉", done: true },
],
};
render() {
const {todos} = this.state
// 直接通过 props 传递
return (
<div>
<List todos={todos}/>
</div>
);
}
}
子组件
子组件通过 this.props
接收数据
import React, { Component } from 'react'
export default class index extends Component {
render() {
const {todos} = this.props
return (
<div >
<h1>待办清单</h1>
{
todos.map((todo)=>{
return <h3>todo.name</h3>
})
}
</div>
)
}
}
父组件 为了接收来自子组件的数据,需要预定义一个函数,将函数通过 props 传递给子组件
import React, { Component } from "react";
import List from "./component/List";
export default class App extends Component {
// 初始化状态
state = {
todos: [
{ id: "1", name: "吃饭", done: true },
{ id: "2", name: "睡觉", done: true },
],
};
// 添加一个 todo 对象,用于子组件向父组件传递参数
addTodo = (todoObj) => {
const todos = this.state.todos;
const newTodos = [todoObj, ...todos];
this.setState({ todos: newTodos });
};
render() {
const {todos} = this.state
// 通过函数传递给子组件
return (
<List todos={todos} addTodo={this.addTodo}/>
);
}
}
子组件 子组件接收到来自父组件的函数,通过调用函数实现数据传递
import React, { Component } from 'react'
export default class index extends Component {
handleKeyUp = (event) => {
const {keyCode, target} = event;
if(keyCode !== 13) return
if(target.value.trim() === ""){
alert("输入不能为空")
return
}
const todoObj = {id: nanoid(), name: target.value, done: false}
// 在子组件中,调用父组件函数,传递参数给父组件
this.props.addTodo(todoObj)
target.value = ''
}
render() {
const {todos} = this.props
return (
<div >
<input onKeyUp={this.handleKeyUp} type="text" placeholder='请输入待办事项'/>
<h1>待办清单</h1>
{
todos.map((todo)=>{
return <h3>todo.name</h3>
})
}
</div>
)
}
}