【问题标题】:Style not getting overwritten in react-native using styled-components在 react-native 中使用 styled-components 不会覆盖样式
【发布时间】:2022-01-04 00:46:00
【问题描述】:

我正在尝试使用 styled-components 覆盖调用组件中的按钮属性,但它不起作用。没有任何内容被覆盖,并且组件看起来好像没有采用被覆盖的属性。

我有一个这样定义的按钮:

import React from 'react';
import { TouchableHighlight, View, Text, StyleSheet } from 'react-native';

type ButtonProps = {
  text: string;
};

export const RegularButton = ({text}: (ButtonProps)) => {

  var [ isPress, setIsPress ] = React.useState(false);

  var touchProps = {
    activeOpacity: 1,
    underlayColor: '#111111',
    style: isPress ? (styles.btnPress) : (styles.btnNormal),
    onHideUnderlay: () => setIsPress(false),
    onShowUnderlay: () => setIsPress(true),
    onPress: () => console.log('HELLO'),
  };

  return (
    <TouchableHighlight  {...touchProps}>
      <Text style={styles.textStyle}>{text}</Text>
    </TouchableHighlight>
  );
}

var styles = StyleSheet.create({
  btnNormal: {
    backgroundColor: '#333333',
    borderColor: 'black',
    borderWidth: 1,
    borderRadius: 10,
  },
  btnPress: {
    borderColor: 'black',
    borderWidth: 1,
    borderRadius: 10,
  },
  textStyle: {
    color: '#a7a7a7',
    margin: 'auto'
  }
});

还有一个使用它并使用 styled-components 覆盖样式的 App 模块:

import React from 'react';

import styled from "styled-components";
import { RegularButton } from './components/core/RegularButton'

const MainView = styled.div`
  width: 100%;
  height: 100%;
  background-color: #1a1a1a;
  flex: 1;
  align-items: 'center';
  justify-content: 'center';
`;

const LevelButton = styled(RegularButton)`
  width: 100%;
  height: 60px;
  margin-left: 16px;
  margin-right: 16px;
`;


export default function App() {
  return (
    <MainView>
      <LevelButton text={"hello"}/>
      <LevelButton text={"hello"}/>

    </MainView>
  );

我在这里做错了什么?我无法让按钮获取我试图覆盖的宽度/高度、边距等属性。

【问题讨论】:

标签: css typescript react-native styled-components


【解决方案1】:

您的 RegularButton 不接受 style 属性。你需要做的是:

style 添加到ButtonProps

type ButtonProps = {
  text: string;
  style?: StyleProp<ViewStyle>;
};

style 传递给组件。


export const RegularButton = ({text, style}: (ButtonProps)) => {

return (
    <TouchableHighlight {...touchProps} style={style}>
      <Text style={styles.textStyle}>{text}</Text>
    </TouchableHighlight>
);

顺便说一句,对于react-native 组件,您应该从styled-components/native 而不是styled-components 导入

【讨论】:

  • 看起来这仍然不起作用。 touchProps 已经定义了一个样式,但即使尝试添加它也没有用: style: [buttonStyle, isPress ? (styles.btnPress) : (styles.btnNormal)],使用上面的方法。如果我完全删除此样式并将其添加到 return 语句中,我试图覆盖的 CSS 属性仍然不会被覆盖。
  • 这很奇怪,我尝试重新创建您的按钮,style 似乎工作。 (顺便说一句,我将样式编辑到TouchableHighlight 的末尾)。如果你想使用一个样式来覆盖以前的样式,你需要把它放在以前的样式之后。像这样:[isPress? (styles.btnPress): (styles.btnNormal), newStyle].
猜你喜欢
  • 2018-04-29
  • 2018-10-20
  • 2020-06-28
  • 2021-08-16
  • 2019-07-15
  • 2021-08-26
  • 2018-01-19
  • 2020-10-19
  • 2020-02-13
相关资源
最近更新 更多