我正在处理我的FormButton.tsx文件。我使用的是React native和TypeScript:
interface Props {
buttonTitle: string;
restProps: any;
}
interface State {}
export default class FormButton extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
}
render() {
const {buttonTitle, ...restProps} = this.props;
return (
<TouchableOpacity>
<Text>{buttonTitle}</Text>
</TouchableOpacity>
);
}
}正如你注意到的,对于restProps,我正在尝试接收这个道具给出的其余道具。但是,这将返回一个错误'restProps' is declared but its value is never read.ts(6133)。
基本上,我想要完成的是能够在const {buttonTitle, ...restProps} = this.props;中解析restProps,然后能够在我的TouchableOpacity上使用它。
你知道怎么解决这个问题吗?
更新:我认为这里有一些混乱。我不是在说简单地接受一个特定的道具。如果我有3个或更多未指定的道具怎么办?如何通过TypeScript在类组件中传播它们。通常,你会在一个普通的功能组件中看到类似这样的东西:
const FormButton = ({buttonTitle, ...rest}) => {
return (
<TouchableOpacity style={styles.buttonContainer} {...rest}>
<Text style={styles.buttonText}>{buttonTitle}</Text>
</TouchableOpacity>
);
};如何将其转换为TypeScript和React本地类组件?
发布于 2021-09-24 10:45:19
像这样解构一个对象,
const {buttonTitle, restProps} = this.props;现在您将拥有两个变量buttonTitle和restProps。
发布于 2021-11-20 21:47:58
@哈里特·拉斯托吉的答案是正确的。而是为功能组件用户提供道具界面。
import React from "react";
import { StyleSheet, Text, TouchableOpacity } from "react-native";
interface Props {
buttonTitle: string;
[x: string]: any; //please comment if you know better type than any
}
const FormButton: React.FC<Props> = (props) => {
const { buttonTitle, ...rest } = props;
return (
<TouchableOpacity style={styles.buttonContainer} {...rest}>
<Text style={styles.buttonText}>{buttonTitle}</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
// Your button-container style here
buttonContainer: {},
buttonText: {},
});
export default FormButton;然后你可以像这样使用它:
<FormButton
buttonTitle="Testing Button"
onPress={() => console.log("foo")}
/>如果您只想添加样式:
import React from "react";
import { StyleProp, StyleSheet, View, ViewStyle } from "react-native";
interface Props {
style?: StyleProp<ViewStyle>;
}
const Card: React.FC<Props> = ({ children, style }) => {
return <View style={[styles.card, style]}>{children}</View>;
};
const styles = StyleSheet.create({
card: {}
});
export default Card;然后你可以像这样使用(你也会得到自动补全):
<Card style={{ width: 500 }}>
</Card>https://stackoverflow.com/questions/69313605
复制相似问题