【问题标题】:Applying styles in react native with styled components在带有样式的组件的本机反应中应用样式
【发布时间】:2019-03-24 03:15:34
【问题描述】:

我有一个组件 Logo,我试图在其中应用宽度和高度:

import styledNative from "styled-components/native";
import {Image, View} from "react-native"
import companyIcon from "../svg/companyIcon.svg";

const Logo = () => (
  <Image source={{uri: companyIcon}} />;
);

const StyledLogo = styledNative(Logo)`
  width: 48px;
  height: 48px;
`;

const Header = () => {
  return (
    <View>
      <StyledLogo />
    </View>
  );
};

这给我们留下了一个不可见的徽标,宽度为 0。样式组件文档似乎建议使用传入的 className 属性 (https://www.styled-components.com/docs/advanced#existing-css),但这似乎适用于标准样式组件,而不是 react- native / react-native-web 实现,因为它只是没有传递给我的组件。当我检查传递的 Logo 道具(通过控制台记录它们)时,有 is 一个样式对象,但这似乎不是我可以使用的任何东西,并且在样式中没有太多提及它组件文档:

style: Array(2)
  0: 91
  1: undefined
  length: 2

所以我不太确定如何处理它。 styled-components如何给组件设置样式?

【问题讨论】:

    标签: react-native styled-components


    【解决方案1】:

    您没有将样式应用于图像。

    现在发生的情况是,您的 Logo 组件正在接收这些样式道具,但它没有传递它们。

    const Logo = (props) => ( // <-- containing style props
      <Image source={{uri: companyIcon}} />;
    );
    

    所以您想要做的是将您的 Logos 道具传播到您的图像上,以便它获取所需的数据。

    const Logo = (props) => ( // <-- containing style props
      <Image {...props} source={{uri: companyIcon}} />;  // <-- styles now applied to Image
    );
    

    或者你也可以只通过 style-props。

    const Logo = (props) => ( // <-- containing style props
      <Image source={{uri: companyIcon}} style={props.style}/>;
    );
    

    编辑: 您似乎也传递了无效的样式。 React Native 期望你传入的值没有单位。因此,您的样式应该是 width: 48;,而不是 ...px。

    【讨论】:

    • 感谢您的回答 - 但传递给 Logo 的样式对象只是一个包含两项的数组,一项为数字 (91),另一项未定义。如果我这样做:export default ({style}) =&gt; { return &lt;Image source={{uri: companyIcon}} style={style} /&gt;; }; 我只会得到一个警告:“ID 为 91 的样式无效。跳过...”。如果我尝试传递所有道具:export default (props) =&gt; { return &lt;Image source={{uri: canopyIcon}} {...props} /&gt;; }; 我最终会收到相同的“无效样式”警告
    • 嗯。样式实际上可以是一个传递多个数组的数组,据我所知,使用StyleSheet 创建的样式在此处显示为数字引用,而不是对象。如果我没记错的话,您应该可以使用StyleSheet.flattenStyles 来获取您的样式的实际对象表示。
    • 哦,对了。样式可能无效,因为您传递了...px。您的样式应该只是 RN 中没有单位的数字!
    猜你喜欢
    • 1970-01-01
    • 2020-12-03
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2018-04-29
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多