简体   繁体   中英

Why doesn't this style property assignment work as expected in React Native?

I've tested the below code on React Native in my browser (using Expo CLI Webpack) and the result is three green squares down the left side of the screen.

 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;

However, I expected to see a red, green and blue square. I've tried to mimic a pattern used several times on this page of the RN documentation but it isn't behaving as I expected. Could someone please explain what I've misunderstood here? Thanks.

Props will be passed as a single object attribute, not as multiple attributes.

Simply replace (label, value) with ({label, value}) .

By putting curly braces around your props you're destructing the first attribute, which in this case is your props.

There are two issues with your code.

First, as Ugur Eren mentioned, you are not destructuring your props.

Second, you are putting your styles objects into an array .

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
  );
};

Using Spread Syntax allows you to build a new object, stacking values that are passed in (or build a new array, appending values that are passed in).

It looks like this is already what you are trying to do, except you were using an array (which won't overwrite/stack values) and missing the spread syntax operator ( ... ).

Edit: array syntax correct

Looks like I'm wrong about this -- the Array syntax for style is correct. It is used in the official React Native documentation on style :

        <Text style={[styles.bigBlue, styles.red]}>bigBlue, then red</Text>

Weirdly, there is no mention of this in the React documentation on style, neither on the DOM elements page nor in the FAQ on styling , which only mention using Objects to pass style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM