在React Native with TypeScript中创建自定义组件
我决定将我的ReactNative项目转换为TypeScript。我是TypeScript新手,发现很难用自定义组件和继承来解决这个问题。这是我的(缩小)代码在React Native with TypeScript中创建自定义组件,typescript,react-native,Typescript,React Native,我决定将我的ReactNative项目转换为TypeScript。我是TypeScript新手,发现很难用自定义组件和继承来解决这个问题。这是我的(缩小)代码 import React,{Component}来自“React”; 从“react native”导入{按钮,视图}; 接口IMyComponentProps扩展React.Props{ colWidth?:数字; } 类MyComponent扩展组件{ getProps(){ 归还这个道具; } } 类MyButton扩展MyComp
import React,{Component}来自“React”;
从“react native”导入{按钮,视图};
接口IMyComponentProps扩展React.Props{
colWidth?:数字;
}
类MyComponent扩展组件{
getProps(){
归还这个道具;
}
}
类MyButton扩展MyComponent{
render(){
返回(
);
}
}
我在MyButton组件中的这个.getProps()上得到了一条红色下划线。此外,未识别this.props.title和this.props.onPress
你能帮我定义这两个类的类型吗
谢谢首先,您需要声明
MyButton
具有更具体的道具,因此必须将MyComponent
参数化:
class MyComponent<P extends IMyComponentProps> extends Component<P> {
getProps() {
return this.props
}
}
然后,除非您使用的是难以解释的refs,不要扩展React.Props
。只需将接口声明为:
interface IMyComponentProps {
colWidth?: number;
}
interface IMyButtonProps extends IMyComponentProps {
title: string;
onPress: () => void;
}
现在全部
我
mport React,{Component}来自“React”;
从“react native”导入{按钮,视图};
接口IMyComponentProps{
colWidth?:数字;
}
类MyComponent扩展组件
{
getProps(){
归还这个道具
}
}
接口IMyButtonProps扩展了IMyComponentProps{
标题:字符串;
onPress:()=>无效;
}
类MyButton扩展MyComponent{
render(){
返回(
);
}
}
interface IMyButtonProps extends IMyComponentProps {
colWidth?: number;
title: string;
onPress: () => void;
}
class MyButton extends MyComponent<IMyButtonProps> {
render() {
return (
<View {...this.getProps()}>
<Button title={this.props.title} onPress={this.props.onPress} />
</View>
);
}
}
interface IMyComponentProps {
colWidth?: number;
}
interface IMyButtonProps extends IMyComponentProps {
title: string;
onPress: () => void;
}
mport React, { Component } from "react";
import { Button, View } from "react-native";
interface IMyComponentProps {
colWidth?: number;
}
class MyComponent<P extends IMyComponentProps> extends Component<P> {
getProps() {
return this.props
}
}
interface IMyButtonProps extends IMyComponentProps {
title: string;
onPress: () => void;
}
class MyButton extends MyComponent<IMyButtonProps> {
render() {
return (
<View {...this.getProps()}>
<Button title={this.props.title} onPress={this.props.onPress} />
</View>
);
}
}