javascript - TypeScript 属性需要什么数据类型传递给 React 组件中的函数
问题描述
我正在创建一个基本的 TypeScript React 项目来熟悉 React 和 TypeScript,因为我以前从未使用过这两种技术。
下面是一个基本组件,作为我正在学习的课程的一部分,我将它放在一起,但是该课程没有使用 TypeScript,所以我必须在进行时进行调整。
据我了解 TypeScript,您必须明确说明您在组件中使用的每个属性的数据类型。现在我试图引入一个“点击”属性,我将向它传递一个函数,但我不知道哪种数据类型是必要的。
import React, { MouseEventHandler } from 'react';
type PersonProps = {
name: string,
age: number,
children: string,
click?:
}
const Person = ({name, age, children, click}: PersonProps) => (
<div>
<p onClick={click}>I'm {name} and I'm {age} years old.</p>
<p>{children}</p>
</div>
);
export default Person;
下面是我将函数传递到属性字段的代码
const App = () => {
const [personsState, setPersonsState] = useState({
persons: [
{ name: 'Max', age: 16},
{ name: "Theo", age: 27},
{ name: "Tom", age: 63}
],
otherState: 'some other value'
});
const [otherState, setotherState] = useState('Some other value');
console.log(personsState, otherState);
const switchNameHandler = () => {
setPersonsState({
persons: [
{ name: 'Jeff', age: 16},
{ name: "Bob", age: 27},
{ name: "Kyle", age: 90}
],
otherState: personsState.otherState
});
};
return (
<div className="App">
<h1>Hi, I'm a React App</h1>
<p>This is really working!</p>
<button onClick={switchNameHandler}>Switch Name</button>
<Person
name={personsState.persons[0].name}
age={personsState.persons[0].age}>My Hobbies: Racing</Person>
<Person
name={personsState.persons[1].name}
age={personsState.persons[1].age}
click={switchNameHandler}>My Hobbies: Sleep</Person>
<Person
name={personsState.persons[2].name}
age={personsState.persons[2].age}>My Hobbies: Design</Person>
</div>
);
}
我尝试使用MouseEvent
作为数据类型,但没有成功。
解决方案
你可以加
type PersonProps = {
name: string,
age: number,
children: string,
click?: () => void,
}
尽管如果将此单击属性绑定到 onClick,则该函数的默认参数将是SyntheticEvent类型
click?: (SyntheticEvent e) => void
推荐阅读
- javascript - 重定向到 Javascript 中的动态链接不起作用
- vue.js - 为什么不能使用 v-on 简写来绑定“on”?
- python - Elasticsearch 找不到关键字搜索
- bash - 将 awk 的 1 个字段转换为 base64,其余部分保持不变
- java - 如何将 keycloak 离线访问令牌存储在本地数据库中?
- javascript - 当我更改在 React 中传递给它的道具时,组件没有更新
- c# - 与实体框架的asp net core mysql连接
- metadata - 如何使用元数据生成 SAML 断言响应?
- android - contentResolver.openInputStream(uri) 在获取安全权限被拒绝时崩溃
- r - R:将带有选项卡的txt保存为行的标题