[英]React with typescript passing function as props using hooks
I am pretty new to typescript.我对打字稿很陌生。 trying to build a simple crud app with react, typescript and hooks.
尝试使用 react、typescript 和 hooks 构建一个简单的 crud 应用程序。 I can't figure out how to pass data and function together as props to a child component that will further send props to his chid.
我不知道如何将数据和函数一起作为道具传递给子组件,该子组件将进一步将道具发送给他的孩子。 Here is a sample code.
这是一个示例代码。
const App = () => {
const [data, setData] = useState([
{ id: 1, name: 'John', email: 'john@gmail.com' },
{ id: 1, name: 'Mike', email: 'mike@gmail.com' },
])
// how to send this function to StudentList component
const removeStudent = (id: number): void => {
setData(data.filter(item => item.id !== id))
}
return (
<div>
<StudentList data={data} removeStudent={removeStudent} />
</div>
);
}
interface StudentsInterface {
id: number,
name: string,
email: string,
}
interface PropsFunction {
removeStudent: () => void
}
const StudentList = ({ data }: { data: StudentsInterface[] }, { removeStudent }: PropsFunction) => {
console.log('removeStudent ==>', removeStudent) // getting undefined
return (
<table id='students'>
<tbody>
{data.map((student, index) => {
return (
<Student student={student} key={index} removeStudent={removeStudent} />
)
})}
</tbody>
</table>
)
}
If I just pass data (first parameter of StudentList), I get the props, but I want removeStudent function too...如果我只是传递数据(StudentList 的第一个参数),我会得到道具,但我也想要 removeStudent 函数......
If it is just react I know I would just destructure {removeStudent} in studentList and I am done, but here in typescript I have to define data type...如果只是反应,我知道我只会在 studentList 中解构 {removeStudent} 并且我完成了,但是在打字稿中我必须定义数据类型......
Hope I am clear.希望我清楚。 Since I am pretty new to typescript I would be glad if you explain what I am doing wrong.
由于我对打字稿很陌生,如果您解释我做错了什么,我会很高兴。
You're using 2 arguments as props:您使用 2 个参数作为道具:
const StudentList = ({ data, removeStudent }: { data: StudentsInterface[], removeStudent: PropsFunction }) => ...
EDIT:编辑:
One way to fix it is that you have defined PropsFunction
as an interface, meaning it is an object with a property removeStudent
- you probably just want it to be:修复它的一种方法是您已将
PropsFunction
定义为一个接口,这意味着它是一个具有属性removeStudent
的对象 - 您可能只是希望它是:
type PropsFunction = () => void;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.