![](/img/trans.png)
[英]JavaScript - Why doesn't the addition assignment operator work as expected?
[英]Why doesn't this style property assignment work as expected in React Native?
我已经在浏览器中的 React Native 上测试了以下代码(使用 Expo CLI Webpack),结果是屏幕左侧下方的三个绿色方块。
import React, { useState } from "react"; import { View, TouchableOpacity, Text, StyleSheet } from "react-native"; const styles = { width: 100, height: 100, backgroundColor: "green" }; const Rectangle = (label, value) => { return ( <View style={[styles, {[label]: value}]}/> // Line I expect to modify style.backgroundColor ); }; const Page = () => { return ( <View style={{flex: 1, justifyContent: "space-evenly"}}> <Rectangle label="backgroundColor" value="red" /> <Rectangle label="backgroundColor" value="green" /> <Rectangle label="backgroundColor" value="blue" /> </View> ); }; export default Page;
但是,我预计会看到一个红色、绿色和蓝色的方块。 我试图模仿在 RN 文档的这个页面上多次使用的模式,但它的行为不像我预期的那样。 有人可以解释一下我在这里误解了什么吗? 谢谢。
道具将作为单个对象属性传递,而不是作为多个属性传递。
只需将(label, value)
替换为({label, value})
。
通过在你的道具周围放置花括号,你正在破坏第一个属性,在这种情况下是你的道具。
您的代码有两个问题。
首先,正如 Ugur Eren 提到的,你并没有破坏你的道具。
其次,您将样式对象放入数组中。
const Rectangle = ({label, value}) => { //<-- use destructuring. See Ugur Eren answer
return (
<View style={{...styles, [label]: value}}/> //<-- use an object. Use spread syntax to stack values
);
};
使用Spread Syntax允许您构建一个新对象,堆叠传入的值(或构建一个新数组,附加传入的值)。
看起来这已经是您正在尝试做的事情,除了您使用的是数组(不会覆盖/堆叠值)并且缺少扩展语法运算符( ...
)。
看起来我错了——样式的数组语法是正确的。 它在关于 style的官方 React Native 文档中使用:
<Text style={[styles.bigBlue, styles.red]}>bigBlue, then red</Text>
奇怪的是,React 的样式文档中没有提到这一点,无论是在 DOM 元素页面还是在关于样式的常见问题解答中,都只提到使用对象来传递样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.