Reactjs 为什么泛型与Typescript中的类组件一起使用
我在学习React with Typescript,因为我想创建类组件,所以我们需要使用如下泛型:Reactjs 为什么泛型与Typescript中的类组件一起使用,reactjs,typescript,Reactjs,Typescript,我在学习React with Typescript,因为我想创建类组件,所以我们需要使用如下泛型: type MyProps = { // using `interface` is also ok message: string; }; type MyState = { count: number; // like this }; class App extends React.Component<MyProps, MyState> { state: MyState
type MyProps = {
// using `interface` is also ok
message: string;
};
type MyState = {
count: number; // like this
};
class App extends React.Component<MyProps, MyState> {
state: MyState = {
// optional second annotation for better type inference
count: 0,
};
render() {
return (
<div>
{this.props.message} {this.state.count}
</div>
);
}
}
function identity<T>(arg: T): T {
return arg;
}
type MyProps={
//使用“interface”也可以
消息:字符串;
};
类型MyState={
count:number;//像这样
};
类应用程序扩展了React.Component{
状态:MyState={
//可选的第二个注释用于更好的类型推断
计数:0,
};
render(){
返回(
{this.props.message}{this.state.count}
);
}
}
好的,正如我的研究所说,泛型有助于实现可重用性,例如,当我们用如下的泛型创建函数时:
type MyProps = {
// using `interface` is also ok
message: string;
};
type MyState = {
count: number; // like this
};
class App extends React.Component<MyProps, MyState> {
state: MyState = {
// optional second annotation for better type inference
count: 0,
};
render() {
return (
<div>
{this.props.message} {this.state.count}
</div>
);
}
}
function identity<T>(arg: T): T {
return arg;
}
函数标识(arg:T):T{
返回arg;
}
但我无法理解的是,为什么我们需要在这里使用泛型
类App extensed React.Component
?重用不是这里的主要问题,即使在这种情况下,React.Component
被重用
泛型有不同的用途,即允许以类型安全的方式自定义道具和状态成员。请记住,Typescript在Javascript之上增加了类型安全性,因此类成员等必须使用类型定义
在您的示例中,没有您的MyState
类型,就没有组件应该为其状态成员使用的信息,当您使用类似this.state.count
的内容时,您将得到一个错误。只有当Typescript知道实际应该存在什么时,它才能确保正确性
旁注:React本身有一个机制来提供类型安全性,即使没有Typescript。您可以在React主页上找到有关的更多信息。但是我会随时推荐Typescript,而不是PropTypes,它指定了很多东西,例如方法的签名:
render():反应节点代码>
构造函数(道具:只读
)代码>
泛型提供了一种方法来指定在所有方法的类型定义中允许哪些具体的属性和状态。如果不允许,您将如何指定组件状态及其属性的类型?@zerkms,No))我刚刚从某个资源中获取了这个示例,我只是想创建类组件,但发现了一个示例,它表明我们需要使用泛型,因此我想问一下为什么?)我的评论部分回答了这个问题:这样您就可以指定组件的状态和道具的类型。@zerkms,好吧,但确切地说,为什么要通过泛型?我们不能使用类App extends React.Component并使用类似以下状态的类型:MyState。我确信这背后有原因,但找不到原因:)泛型是类型参数。与调用函数时将参数传递给函数的方式相同,在将类型参数传递给泛型类型时,泛型类型将被实例化。