當嘗試為我的 react native 應用程式獲取適當的樣式時,它說它不適用于按鈕樣式。
如何使型別錯誤消失?
interface TextButtonProps {
buttonStyle?: StyleProp<ViewStyle>;
labelStyle?: StyleProp<TextStyle>;
click: () => void;
text: string;
}
interface Styles {
button: ViewStyle;
icon: ImageStyle;
label: TextStyle;
}
const TextButton: React.SFC<TextButtonProps> = ({ buttonStyle, text, click }): JSX.Element => {
const styles = StyleSheet.create<Styles>({
button: buttonStyle,
});
錯誤:
Type 'StyleProp<ViewStyle>' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'.
Type 'undefined' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'.ts(2322)
TextButton.tsx(13, 3): The expected type comes from property 'button' which is declared here on type 'Styles | NamedStyles<Styles>'
uj5u.com熱心網友回復:
問題是buttonStyle可能是undefined并且該方法create不支持該值undefined
buttonStyle?: StyleProp<ViewStyle>; // ? means it can be undefined (a.k.a optional)
您必須檢查buttonStyleis not undefined,您可以通過以下方式進行:
const TextButton: React.SFC<TextButtonProps> = ({ buttonStyle, text, click }): JSX.Element => {
if (!buttonStyle) return; // Or a proper alternative return value
const styles = StyleSheet.create<Styles>({
button: buttonStyle,
});
}
或者,如果您 100% 確定在傳遞buttonStyle引數時它不會是nullor undefined,您可以使用非空斷言運算子!
const TextButton: React.SFC<TextButtonProps> = ({ buttonStyle, text, click }): JSX.Element => {
const styles = StyleSheet.create<Styles>({
button: buttonStyle!, // <--- Here
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443809.html
上一篇:輸出結果為空白,結果引數未定義?
下一篇:了解反應原生導航
