【问题标题】:React-Native SVG backgroundReact-Native SVG 背景
【发布时间】:2022-01-12 20:07:45
【问题描述】:

我正在尝试在 React-Native 中使用 SVG 获取背景图案。

我使用“react-native-svg”库创建了一个组件,如下所示:

import React from "react";
import { SvgXml } from "react-native-svg";

const xml = `
  <svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
    <g
      fill='#ffb6c1'
      fill-opacity='0.2'
    >
      <polygon 
        fill-rule='evenodd'
        points='8 4 12 6 8 8 6 12 4 8 0 6 4 4 6 0 8 4'
      />
    </g>
  </svg>
`;

export default () => <SvgXml xml={xml}  />;

然后我尝试将其导入 App.js,如下所示:

import React from 'react';
import { StyleSheet, ImageBackground, Text, View } from 'react-native';
import Header from './components/Header'
import SVG from './assets/4-point-star'

export default function App() {
  return (
    <View  style={styles.container}>
      <ImageBackground source={{uri: SVG}} style={styles.image}>
      <View>
        <Text style={styles.text}>Open up App.js to start working on your app!</Text>
      </View>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: 'black',
    color: 'white',
    alignItems: 'center',
    justifyContent: 'center',
},
  image: {
    width: '100%',
    height: '100%',
  },
  text: {
    color: 'white'
  },
});

但是,我在设备上收到以下错误:

感谢任何帮助

谢谢

【问题讨论】:

    标签: reactjs react-native svg


    【解决方案1】:

    ImageBackground(继承了 Image 属性)doesn't support 组件或任何不应该是图像文件的东西。
    所以你必须直接使用 Svg 组件并为其设置样式。
    您也可以使用在线工具svgr将svg直接转换为组件。

    假设您将其作为接收参数的组件(如 svgr 制作),您可以将其用作(全尺寸)背景,例如:

    import { Dimensions } from "react-native";
    const { width, height } = Dimensions.get("window");
        
    ...
    <>
        ...
        <SVG width={width} height={height} style={{ zIndex: -1, elevation: -1 }} />
        <View>
            ...
        </View>
    </>
    

    或者只是根据需要编辑高度/宽度。

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,我发现当我在网络上运行我的应用程序并将视图更改为 Iphone 时会发生这种情况。我正在使用 expo,所以我使用 Expo Go 应用程序读取了 QR 码,我看得很清楚。我到处看了看,我的代码似乎是正确的,我把我的 SVG 作为一个组件返回了,就像之前有人说的那样。

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 1970-01-01
        • 2019-12-16
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2019-06-18
        • 2018-09-03
        • 2021-04-10
        相关资源
        最近更新 更多