我对打字稿很陌生。尝试使用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>
);
}
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}并完成,但是在打字稿中,我必须定义数据类型...
希望我很清楚。 由于我对打字稿还很陌生,如果您能解释我做错了什么,我会很高兴。
答案 0 :(得分:1)
您使用2个参数作为道具:
const StudentList = ({ data, removeStudent }: { data: StudentsInterface[], removeStudent: PropsFunction }) => ...
编辑:
一种解决方法是将PropsFunction
定义为接口,这意味着它是具有属性removeStudent
的对象-您可能只希望它是:
type PropsFunction = () => void;