react-native - 如何将道具中的值应用于样式?
问题描述
我创建了一个自定义组件:
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
样式中看到的那样,我尝试使用size
andcolor
传入 via props
。
我通过Square
以下方式在另一个组件中使用:
<Square size={30} color="black" .../>
但是,运行我的应用程序时不会应用大小和颜色。
那么,如何在自定义组件的样式中使用传入的值?
解决方案
有几种方法可以在您的 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',
},
});
推荐阅读
- javascript - 如何在 OpenLayers 中重叠或相同几何体的情况下选择哪个要素叠加
- python - 使用 python-chess 从 PGN 文件中提取移动作为字符串
- reactjs - 部署在 Heroku 上的 ExpressJS API 出现 500 内部服务器错误
- excel - 类型不匹配 - 范围和数字
- javascript - 当对象是 JSON 对象与 Array 对象时,为什么 [For.. in] 循环中使用的变量返回不同的值?
- python - 在 python 中复制 F# map join
- c# - Unity C# 函数 Application.CanStreamedLevelBeLoaded(String string) 有什么作用?
- python - index() 函数不起作用,较长的函数也无法找到包含最大/最小数的行号
- c - CMake:未评估目标属性中的生成器表达式
- angular - 尝试更新云 Firestore 中的字段