I want to define a function that the parent component passes to the child component, but I don't know how to write the arguments.
Please let me know if anyone understands.
**types.ts**
export type Task {
id:number
text:string
done —boolean
}
// Parent component
import React, {useState} from 'react'
import {Task} from './Types'
// Set initial value
constinialState: Task[] = [
{
id: 0,
text:",
done —false,
}
]
constApp:React.FC=()=>{
const [text, setText] = useState(')
const [task, setTask] = useState(internalState);
// What to do when the check box is pressed (I want to pass it to ListItem)
consthandleCheck=(What should I put in) =>{
setTasks(prev=>prev.map(t=>
t.id === task.id
? {...task, done:!task.done}
: t
))
}
// Action when the Delete button is pressed (I want to pass it to ListItem)
consthandleDelete=(What should I put in) =>{
setTasks(prev=>prev.filter(t=>
t.id!==task.id
))
}
return(
Omitted.
<div>
<TaskList/>
</div>
)
}
child components
import React from 'react'
import TaskItem from'./TaskItem'
import {Task} from './Types'
interface Props {
text:string
tasks —task [ ]
HandleCheck:
handleDelete:
}
const TaskList:React.FC<Props>=({props})=>{
return(
~ Omitted.
)
}
export default TaskList
To pass values from parent to child, for example,
in render()render(){
return(
<ChildComponent
listItem = {this.state.listItem}
onChange={this.handleChange}/>
);
}
Pass the child components when they are rendered from the parent component, as shown in .
The "What should I put in" part is used to pass the return value from the child component to the parent component.For example, if a child component updates ListItem, the parent component receives the updated data and determines whether it is reflected in the state, etc.
handleChange(updatedElementId,data){
constupdatedItems=this.state.listItems.slice();
updatedItems [updatedElementId] = data;
This.setState({
listItems—updatedItems
});
}
as shown in .
Data is passed only when the parent component renders the child component, and when the child component updates data, the child component reports to the parent component handleChange through onChange, and then updates this.state of the parent component to transfer the data back to the child component and so on.
© 2024 OneMinuteCode. All rights reserved.