gpt4 book ai didi

reactjs - 无法读取未定义的属性 'width' (style.width)

转载 作者:行者123 更新时间:2023-12-03 13:27:27 27 4
gpt4 key购买 nike

好的,所以我得到了 ImageBackground 的以下组件(使用 typescript ,但应该是不言自明的)。 (这是 react 原生的)

import * as React from "react";
import { ImageBackground, ImageURISource } from "react-native";
import { width as deviceW } from "../services/device";

type Props = {
width: number;
ratio: number;
unit: "px" | "%";
source: ImageURISource;
};

class AspectRatioBackground extends React.Component<Props> {
render() {
const { width, ratio, unit, ...props } = this.props;
let w = width;
let h = width * ratio;
if (unit === "%") {
w = deviceW * (width / 100);
h = deviceW * (width / 100) * ratio;
}
console.log(w, h);
return <ImageBackground style={{ width: w, height: h }} {...props} />;
}
}

export default AspectRatioBackground;

它的使用方式是这样的

    <AspectRatioBackground
source={pressed ? activeBackgroundUrl : backgroundUrl}
width={55}
unit="%"
ratio={0.2946}
>
<View pointerEvents="none">
<String>{children}</String>
</View>
</AspectRatioBackground>

该控制台日志返回正确的数值,即 100200,但由于某种原因,我收到以下错误:

类型错误:无法读取未定义的属性“宽度”

This error is located at: in ImageBackground (at AspectRatioBackground.js:25) in AspectRatioBackground (at Button.js:61) in TouchableWithoutFeedback (at Button.js:60) in Button (at SignInEmailPage.js:22) in SignInEmailPage (created by Route) in Route (created by withRouter(SignInEmailPage)) in withRouter(SignInEmailPage) (created by Route) in Route (at _Onboarding.js:44) in Switch (at _Onboarding.js:43) in RCTView (at View.js:71) in View (at createAnimatedComponent.js:147) in AnimatedComponent (at OnboardingRouteAnimation.js:33) in OnboardingRouteAnomation (at _Onboarding.js:42) in RCTView (at View.js:71) in View (at ImageBackground.js:68) in ImageBackground (created by Styled(ImageBackground)) in Styled(ImageBackground) (at _Onboarding.js:32) in Onboarding (created by Route) in Route (created by withRouter(Onboarding)) in withRouter(Onboarding) (at index.js:20) in LayoutIndex (created by Route) in Route (created by withRouter(LayoutIndex)) in withRouter(LayoutIndex) (at index.js:13) in Router (created by MemoryRouter) in MemoryRouter (at NativeRouter.js:11) in NativeRouter (at index.js:12) in Provider (at index.js:11) in App (at renderApplication.js:35) in RCTView (at View.js:71) in View (at AppContainer.js:102) in RCTView (at View.js:71) in View (at AppContainer.js:122) in AppContainer (at renderApplication.js:34)

最佳答案

提供 style支持ImageBackground (即使是像 <ImageBackground style={{}}.../> 这样的空的)也可以解决问题。

这是因为internals of the component正在尝试阅读widthheight来自(扁平化)样式 Prop 。因此“无法读取...未定义的”

documentation for this component

Note that you must specify some width and height style attributes.

关于reactjs - 无法读取未定义的属性 'width' (style.width),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48667989/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com