【问题标题】:How to apply values from props to styles?如何将道具中的值应用于样式?
【发布时间】:2020-07-29 15:59:20
【问题描述】:

我创建了一个自定义组件:

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

const Square = ({size, color, onPress, children}) => {
  return (
    <TouchableOpacity onPress={onPress}>
      <View style={styles.sqr}>{children}</View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  sqr: {
    width: this.size,
    height: this.size,
    backgroundColor: this.color,
    ...
  },
});

export default Square;

正如您在上面的sqr 样式中看到的,我尝试使用通过props 传入的sizecolor

我通过以下方式在另一个组件中使用Square

<Square size={30} color="black" .../>

但是在运行我的应用程序时不会应用大小和颜色。

那么,如何在自定义组件的样式中使用传入的值?

【问题讨论】:

    标签: react-native react-native-stylesheet react-native-component


    【解决方案1】:

    有几种方法可以在您的 react-native 组件中处理条件样式。在您的示例中,您只能在Square 组件本身中访问sizecolor,而不是Stylesheet.create 创建的对象。在这种情况下,通常会将对象列表传递给您可以访问这些值的 style 属性:

    const Square = ({size, color, onPress, children}) => {
      return (
        <TouchableOpacity onPress={onPress}>
          <View
            style={[styles.sqr, { height: size, width: size, color: color }]}
          >
            {children}
          </View>
        </TouchableOpacity>
      );
    };
    

    由于style 属性接受对象列表,您还可以更进一步地根据传递给组件的道具提供“活动”类。如果您需要从父级传入样式对象并可能打开/关闭一些假设的“活动”样式,这里有一个更复杂的示例:

    const Square = ({size, color, onPress, otherStyles, active, children}) => {
      return (
        <TouchableOpacity onPress={onPress}>
          <View
            style={[
              styles.sqr,
              otherStyles,
              { height: size, width: size, color },
              active ? styles.active : null,
            ]}
          >
            {children}
          </View>
        </TouchableOpacity>
      );
    };
    
    const styles = StyleSheet.create({
      active: {
        backgroundColor: 'red',
      },
    });
    

    【讨论】:

    • 谢谢。现在我还想传递额外的样式,我试过这个 &lt;View style={[styles.sqr, { height: size, width: size, color: color }, otherStyles]} &gt; ,但 otherStyle 没有效果。为什么?
    • otherStyle 来自哪里?它在您的styles 内吗?还是作为道具传入?
    • 作为props传入。我试图传入 marginLeft:30, no effect 。 &lt;Square size={30} color="black" otherStyle={{marginLeft:40}}.../&gt;
    • 你能把你现在正在做的所有事情都包括进来吗?我能够在该列表中正确添加其他样式对象。看到您要执行的操作后,我可以更新我的示例。
    • 我已经更新了我的答案以包含更多示例,希望对您有所帮助。如果您的 otherStyle 属性不起作用,则可能是拼写错误。
    猜你喜欢
    • 2021-11-09
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2012-01-31
    相关资源
    最近更新 更多