首页 > 解决方案 > 不变违规:提供给“样式表生成”预期“数字”的“字符串”类型的无效道具“字体大小” - 样式组件 RN

问题描述

不知道我哪里出错了,我知道 React native 不支持单位,但不支持样式组件来处理这种转换。每次我运行它时,它都会抛出一个错误“样式表生成的值作为字符串,但预期是数字”。当我查看 styled-components 文档时,这种语法似乎很好。

const HomeContainer = styled.View`
  flex: 1;
  background-color: hsl(202, 8%, 90%);
`;

const TaskWrapper = styled.View`
  padding-top: 5rem;
  padding-left: 1.2rem;
`;

const SectionTitle = styled.Text`
  color: hsl(0, 25%, 90%);
  font-size: 1.5rem;
`;

const Home = (props) => {
  return (
    <HomeContainer theme={props.theme}>
      <TaskWrapper>
        <SectionTitle theme={props.theme}> Today's Tasks </SectionTitle
      </TaskWrapper>
    </HomeContainer>
  );
};
export default Home;

错误 :

Running application on sdk_gphone_x86.

Invariant Violation: Invalid prop `fontSize` of type `string` supplied to `StyleSheet generated`, expected `number`.
StyleSheet generated: {
  "color": "hsl(0, 25%, 90%)",
  "fontSize": "1.5rem"
}

This error is located at:
    in StyledNativeComponent (created by Styled(Text))
    in Styled(Text) (at home.js:27)

标签: cssreactjsreact-nativestyled-components

解决方案


目前你不能在 react-native 中rem使用相对单位。em相反,您可以使用pxvalue 来定义您的 fontSize 并将该值用作Number.

您的代码可能看起来像 -

const SectionTitle = styled.Text`
  color: hsl(0, 25%, 90%);
  font-size: 16;
`;

注意:我假设您的fontSize值为16px.


推荐阅读