【发布时间】:2022-07-08 04:33:34
【问题描述】:
当我使用来自“react-native”的<ImageBackground> 和<Image> 组件时,我很难理解为什么打字稿会给我这个错误消息。
错误信息:
没有重载匹配这个调用。 重载 1 of 2,'(props: ImageBackgroundProps | Readonly): ImageBackground',给出了以下错误。 类型'{孩子:元素;风格:{弹性:数字; justifyContent: "flex-end"; }; resizeMode: "封面";来源:任何; }' 不可分配给类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly”。 类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly”上不存在属性“children”。 Overload 2 of 2, '(props: ImageBackgroundProps, context: any): ImageBackground',给出了以下错误。 类型'{孩子:元素;风格:{弹性:数字; justifyContent: "flex-end"; }; resizeMode: "封面";来源:任何; }' 不可分配给类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly”。 类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly”上不存在属性“children”。
主要源代码:
import React from "react";
import {
ImageBackground,
StyleSheet,
View,
} from "react-native";
export default function WelcomeScreen() {
return (
<ImageBackground
style={styles.background}
resizeMode="cover"
source={require("../assets/images/background.jpg")}
>
<View>
<View style={styles.logginButton}></View>
<View style={styles.registerButton}></View>
</View>
</ImageBackground>
);
}
const styles = StyleSheet.create({
background: {
flex: 1,
justifyContent: "flex-end",
},
logginButton: {
width: "100%",
height: 70,
backgroundColor: "#fc5c65",
},
registerButton: {
width: "100%",
height: 70,
backgroundColor: "#4ecdc4",
},
});
因为错误消息听起来像是我无法在 ImageBackground 组件中传递子元素,所以当我将 ImageBackground 组件更改为自关闭元素时(如 <ImageBackground source={image source} /> 错误消息消失了。
我目前使用的另一个解决方案是定义一个引用 expo typescript 模板的自定义组件。在 Themed.tsx 中,模板定义了自定义 <Text> 和 <View> 组件以应用自定义主题。
代码当前有效:
import React from "react";
import {
ImageBackground as DefaultImageBackground,
StyleSheet,
View,
} from "react-native";
type ImageBackgroundProps = DefaultImageBackground["props"] & {
children: React.ReactNode;
};
function MyBackground(props: ImageBackgroundProps) {
return <DefaultImageBackground {...props} />;
}
export default function WelcomeScreen() {
return (
<MyBackground
style={styles.background}
resizeMode="cover"
source={require("../assets/images/background.jpg")}
>
<View>
<View style={styles.logginButton}></View>
<View style={styles.registerButton}></View>
</View>
</MyBackground>
);
}
const styles = StyleSheet.create({
background: {
flex: 1,
justifyContent: "flex-end",
},
logginButton: {
width: "100%",
height: 70,
backgroundColor: "#fc5c65",
},
registerButton: {
width: "100%",
height: 70,
backgroundColor: "#4ecdc4",
},
});
但我觉得我的解决方案没有意义,ImageBackground 组件应该可以带子元素。我的主要源代码中是否有任何语法错误?
【问题讨论】:
-
“听起来我无法在 ImageBackground 组件中传递子元素”是的,这正是错误消息告诉您的内容。 “mageBackground 组件应该能够带孩子”是的,它应该。你用的是什么版本的 react native?