javascript - 使用钩子将 typescript 传递函数作为道具进行反应
问题描述
我对打字稿很陌生。尝试使用 react、typescript 和 hooks 构建一个简单的 crud 应用程序。我不知道如何将数据和函数一起作为道具传递给子组件,该子组件将进一步将道具发送给他的孩子。这是一个示例代码。
父组件
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>
);
}
子组件/StudentList
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>
)
}
如果我只是传递数据(StudentList 的第一个参数),我会得到道具,但我也想要 removeStudent 函数......
如果只是反应,我知道我会在 studentList 中解构 {removeStudent} 并完成,但是在打字稿中我必须定义数据类型......
希望我清楚。由于我对打字稿很陌生,如果您解释我做错了什么,我会很高兴。
解决方案
您使用 2 个参数作为道具:
const StudentList = ({ data, removeStudent }: { data: StudentsInterface[], removeStudent: PropsFunction }) => ...
编辑:
解决它的一种方法是您已将其定义PropsFunction
为接口,这意味着它是具有属性的对象removeStudent
- 您可能只是希望它是:
type PropsFunction = () => void;
推荐阅读
- javascript - 如何在每次单击按钮时显示 3 秒的图像?
- typescript - 在 aws-pulumi 上部署 lambda 函数
- system-verilog - 同一个接口的两个 Modport 有 1 个时钟周期差
- purescript - 在 Purescript 中使用 ADT 的构造函数作为类型
- r - 如果变量中的值重复,请根据其他变量保留具有最低值的行
- azure - 是否可以使用 REST API 获取 Azure 存储帐户连接字符串?
- javascript - js中的动态构造函数名称
- java - install4j 更新 JRE 而不生成新的安装程序
- kivy - KivyMD 无法更改 MDBottomNavigation 的大小
- r - Extract a portion of a string in R