【问题标题】:How to pass props to StyleSheet in React Native using TypeScript?如何使用 TypeScript 在 React Native 中将道具传递给 StyleSheet?
【发布时间】:2021-04-23 12:09:56
【问题描述】:

我想创建一个可以将道具传递给样式表的自定义按钮组件。在这个项目中,我要发送的道具是十六进制代码,因此组件可以根据传递给组件的颜色道具具有不同的颜色。所以,我写了这个

type Props = {
  backgroundColor: string;
  borderColor: string;
};

export const CustomButton = ({
  backgroundColor,
  borderColor,
}: Props) => {

  return (
    <TouchableOpacity
      style={styles({ backgroundColor, borderColor }).container}
    >
    </TouchableOpacity>
  );

const styles = ({ backgroundColor, borderColor }: Props) =>
  StyleSheet.create({
    container: {
      backgroundColor: backgroundColor,
      borderColor: borderColor,
    },
  });

思路是将props传递给组件,然后传递给Touchable组件上的样式。但是,这行不通。这总是在styles({ backgroundColor, borderColor}).container 上给我这个错误

Argument of type "{ backgroundColor, borderColor }" is not assignable to parameter of type "Props".

那么,出了什么问题?我应该如何将道具传递给样式表?

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    你可以这样:

    <TouchableOpacity
     style={[styles.container, { backgroundColor, borderColor }]}
    >
    
    const styles = StyleSheet.create({
     container: {
       // something else style
     },
    });
    

    【讨论】:

    • 这给出了这个错误Property 'container' does not exist on type '({ backgroundColor, borderColor }: Props) =&gt; { container: { backgroundColor: string; borderColor: string; }; }'
    • @arahpanah 更新了,您不再需要将 props 传递给 StyleSheet。
    • 谢谢!有用!只是好奇,为什么我们没有像 style={[styles.container, { backgroundColor: backgroundColor}]} 那样将值传递给 backgroundColor
    【解决方案2】:

    StyleSheet 就像一个静态的东西

    你不应该向它传递参数!

    你应该做的就是使用数组来传递样式

    <TouchableOpacity
        style={[styles.container, { backgroundColor, borderColor }]}
    >
    

    styles.container 是静态部分

    { backgroundColor: borderColor } 是动态部分

    type Props = {
      backgroundColor: string;
      borderColor: string;
    };
    
    export const CustomButton = ({
      backgroundColor,
      borderColor,
    }: Props) => {
    
      return (
        <TouchableOpacity
          style={[styles.container, { backgroundColor, borderColor }]}
        >
        </TouchableOpacity>
      );
    }
    
    const styles = StyleSheet.create({
        container: {
            // put other style like width, border-radius and etc.
        },
    });
    

    如果你不需要设置其他样式,代码就像

    <TouchableOpacity
        style={{ backgroundColor, borderColor }}
    >
    

    【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2021-06-23
    • 2022-01-10
    • 2021-04-01
    • 1970-01-01
    相关资源
    最近更新 更多