這是我的自定義組件的代碼。得到一個錯誤,它不喜歡我給 'type' 字串的型別。定義“型別”的正確方法是什么?我假設我需要為它定義某種型別的物件,但不確定如何去做。
import React from 'react';
import { StyleSheet, Text, Pressable } from 'react-native';
interface Props {
text: string;
type?: string;
onPress: () => void;
}
const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => {
return (
<Pressable
onPress={onPress}
style={[styles.container, styles[`container_${type}`]]}
>
<Text style={[styles.text, styles[`text_${type}`]]}>{text}</Text>
</Pressable>
);
};
export default CustomButton;
const styles = StyleSheet.create({
container: {
width: '100%',
padding: 15,
marginVertical: 5,
alignItems: 'center',
borderRadius: 5,
},
container_PRIMARY: {
backgroundColor: '#3B71F3',
},
container_TERTIARY: {},
text: {
fontWeight: 'bold',
color: 'white',
},
text_TERTIARY: {
fontWeight: 'normal',
color: 'gray',
},
});
uj5u.com熱心網友回復:
由于您嘗試為styles物件使用動態生成的鍵,因此TS 會抱怨,因為該type屬性的string型別可以是任何字串,因此與styles物件中的鍵不匹配。
解決此問題的一種方法是將type屬性轉換為keyof typeof styles:
const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => {
const containerKey = `container_${type}` as keyof typeof styles;
const textKey = `text_${type}` as keyof typeof styles;
return (
<Pressable onPress={onPress} style={[styles.container, styles[containerKey]]}>
<Text style={[styles.text, styles[textKey]]}>{text}</Text>
</Pressable>
);
};
但由于轉換不可靠,您還可以將type屬性的型別設定為string literalTS 型別:
type TERTIARY = 'TERTIARY';
interface Props {
text: string;
type?: 'PRIMARY' | TERTIARY;
onPress: () => void;
}
const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => {
return (
<Pressable onPress={onPress} style={[styles.container, styles[`container_${type}`]]}>
{/* An error would still be displayed here since the styles object doesn't have a text_PRIMARY field */}
{/* <Text style={[styles.text, styles[`text_${type}`]]}>{text}</Text> */}
{/* If there's no other option, you could resort to casting */}
<Text style={[styles.text, styles[`text_${type as TERTIARY}`]]}>{text}</Text>
</Pressable>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/348740.html
標籤:javascript 反应 打字稿 反应原生 世博会
上一篇:ReactNativeButtononPress函式示例
下一篇:反應原生。回傳按鈕重定向到主頁
