Javascript 使用钩子将typescript传递函数作为道具进行反应

Javascript 使用钩子将typescript传递函数作为道具进行反应,javascript,reactjs,typescript,react-hooks,Javascript,Reactjs,Typescript,React Hooks,我对打字很不熟悉。尝试用react、typescript和hook构建一个简单的crud应用程序。我不知道如何将数据和函数作为道具一起传递给子组件,子组件将进一步向他的chid发送道具。下面是一个示例代码 父组件 const-App=()=>{ const[data,setData]=useState([ {id:1,姓名:'John',电子邮件:'john@gmail.com' }, {id:1,姓名:'Mike',电子邮件:'mike@gmail.com' }, ]) //如何将此函数发送到

我对打字很不熟悉。尝试用react、typescript和hook构建一个简单的crud应用程序。我不知道如何将数据和函数作为道具一起传递给子组件,子组件将进一步向他的chid发送道具。下面是一个示例代码

父组件
const-App=()=>{
const[data,setData]=useState([
{id:1,姓名:'John',电子邮件:'john@gmail.com' },
{id:1,姓名:'Mike',电子邮件:'mike@gmail.com' },
])
//如何将此函数发送到StudentList组件
const removeStudent=(id:number):void=>{
setData(data.filter(item=>item.id!==id))
}
返回(
);
}
子组件/学生列表
interface StudentsInterface{
身份证号码:,
名称:string,
电子邮件:string,
}
接口PropsFunction{
removeStudent:()=>无效
}
const StudentList=({data}:{data:StudentsInterface[]},{removeStudent}:PropsFunction)=>{
console.log('removeStudent==>',removeStudent)//未定义
返回(
{data.map((学生,索引)=>{
返回(
)
})}
)
}
如果我只是传递数据(StudentList的第一个参数),我会得到道具,但我也需要removeStudent函数

如果它只是react,我知道我会在studentList中解构{removeStudent},我完成了,但在typescript中我必须定义数据类型

希望我清楚。
由于我对typescript非常陌生,如果您能解释一下我做错了什么,我将非常高兴。

您使用了两个参数作为道具:


const StudentList = ({ data, removeStudent }: { data: StudentsInterface[], removeStudent: PropsFunction }) => ...
编辑:

解决此问题的一种方法是将
PropsFunction
定义为接口,这意味着它是一个具有属性
removeStudent
的对象-您可能只希望它是:

type PropsFunction = () => void;

您使用了两个参数作为道具:


const StudentList = ({ data, removeStudent }: { data: StudentsInterface[], removeStudent: PropsFunction }) => ...
编辑:

解决此问题的一种方法是将
PropsFunction
定义为接口,这意味着它是一个具有属性
removeStudent
的对象-您可能只希望它是:

type PropsFunction = () => void;

我不知道typescript,但在javascript中,您可以使用
const StudentList=({data,removeStudent}=>
,我怀疑typescript版本可能会有类似的要求
const StudentList=({data:StudentsInterface[],removeStudent:PropsFunction}=>
我不知道typescript,但是在javascript中你会做
const StudentList=({data,removeStudent}=>
,我怀疑typescript版本期望类似的东西可能
const StudentList=({data:StudentsInterface[],removeStudent:PropsFunction}=>
好的,我已经获得了作为props的函数,但仍然得到错误“type'(id:number)=>void'中缺少属性'removeStudent',但在type'PropsFunction'中是必需的”现在这个新错误“type'(id:number)=>void'不能分配给type'PropsFunction'@user9258981-当然不是,但那是typescript。-一个类型接受一个参数
(id:number)
,而我发布的
PropsFunction
没有,所以请修复它。我在PropsFunction中传递了一个参数,所以现在它被修复了…谢谢,我已经将我的函数作为props,但我仍然得到了错误“类型中缺少属性'removeStudent'(id:number)=>void'但在类型“PropsFunction”中是必需的。现在,此新错误“type”(id:number)=>void'不可分配给类型“PropsFunction”。@user9258981-当然不是,但这是typescript。-一个类型接受一个参数
(id:number)
而我发布的
PropsFunction
没有,所以请修复它。我在PropsFunction中传递了一个参数,所以现在它已修复…谢谢