【问题标题】:React-native: multiple style props in styled-component and typescriptReact-native:样式组件和打字稿中的多个样式道具
【发布时间】:2020-11-02 07:50:17
【问题描述】:

我正在为我的应用程序使用 React-native 打字稿。我是 React-native 的新手。很多语法对我来说都是新的。对于造型,我使用styled-components。我创建了全局按钮组件。所以,我可以在不同的组件中使用它。我想创建有条件的按钮大小和颜色。所以,我可以操纵父组件的大小和颜色。我可以做两个条件风格的道具。但我不知道如何在 React-native 中执行多个条件。

这是我的 Button 组件

import React from 'react';
import { Text, TouchableHighlight } from 'react-native';
import styled, { css } from 'styled-components/native';


export interface IButton {
  appearance?: "primary" | "secondary" | "dark" | "light";
  children?: string | JSX.Element;
  size?: "small" | "medium" | "big";
  className?: string;
  disabled?: boolean;
  loading?: boolean;
  style?: React.CSSProperties;
  onPress?: () => void;
}

const Button = ({ appearance, children, size, disabled, loading, style, onPress, className }: IButton) => {
  return (
    <ButtonContainer
      className={className}
      onPress={onPress}
      disabled={disabled}
      style={
        disabled ?
          { ...style, "opacity": 0.5, "pointerEvents": `none` } :
          loading ?
            { ...style, "pointerEvents": `none` } :
            style
      }
    >
      {loading ? <Label>loading...</Label> : <Label>{children} </Label>}
    </ButtonContainer>
  );
};


const Label = styled.Text`
  color: white;
  font-weight: 700;
  align-self: center;
  padding: 10px;
`

const ButtonContainer = styled.TouchableHighlight<
  {
    appearance: IButton["appearance"]; // this is my typescript props I don't know how to connect them with my Button styling.
  }
  >`
  width: 50%;
  margin-top: 5px;
  border-color: grey;
  border-width: 2px;
  border-radius: 5px;
  border-radius: 4px;
 background-color:${props => props.primary ? "gray" : "blue"} //
`

export default Button;

这是我使用按钮组件的父组件。

<Button
    size="medium" //this is does not work because I did not style yet
    onPress={() => console.log('hello')}

  >
    click me 
  </Button>

【问题讨论】:

    标签: typescript react-native styled-components


    【解决方案1】:

    style={[disabled &amp;&amp; { opacity: 0.5, pointerEvents: "none" }, loading &amp;&amp; { pointerEvents: "none" }, style ]}

    附:在深入研究 Typescript 和样式化组件等高级主题之前,您应该先坚持基础

    【讨论】:

    • 感谢您的建议,但我的禁用按钮和加载逻辑工作正常。我没有问题。
    猜你喜欢
    • 2021-09-18
    • 2021-07-11
    • 2020-06-03
    • 2019-03-03
    • 2020-08-02
    • 2020-06-27
    • 2021-03-09
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多