[英]Confusion with how interface (TypeScript) is used in React
我是 React 中 TypeScript 的新手,正在学习如何将 TypeScript 正确集成到 React 项目中,并被接口卡住了,也就是说,为什么我们需要在 React 中使用接口? 请帮忙
正如@adiga 指出的那样,接口决定了值的形状。 将 TypeScript 与 React 一起使用时,您可以键入 state 和带有接口的道具。
使用 class 组件的示例(另请参阅此答案):
interface MyProps {}
interface MyState {
foo: string;
bar?: boolean;
}
class MyComponent extends React.Component <MyProps, MyState> {
constructor(props) {
super(props);
this.state = {
// populate state fields according to props fields
};
}
render() {
...
}
}
使用功能组件的示例:
function MyForm(props: myProps) {
...
}
正如这篇Medium 文章所指出的,输入 state 和道具可能有助于跟踪 state 和道具的形状(并防止错误)。 例如,您可能决定在单个文件中定义所有接口(例如src/types/index.tsx
)并将接口导入组件文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.