首页 > 解决方案 > 如何将道具中的值应用于样式?

问题描述

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

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样式中看到的那样,我尝试使用sizeandcolor传入 via props

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

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

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

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

标签: react-nativereact-native-stylesheetreact-native-component

解决方案


有几种方法可以在您的 react-native 组件中处理条件样式。在您的示例中,您只能访问组件本身size及其color内部Square,而不是由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',
  },
});

推荐阅读