如何用道具改变风格

How to change the style with props

如何在 React Native 中更改样式?

我需要在是true还是false的时候改变文字的颜色 这是我的代码:

样式区

LIVE:{
        color: "red"
    },
    Comp: {
        color: "green"
},

主要

<Text style={MyCardStyle.AnyText}>{isLive == false ? /* MyCardStyle.Comp */ : /* MyCardStyle.LIVE */ }</Text>
// The commented out codes have error as "Objects are not valid as a React child"

道具

<MyMatchCard 
    isLive={true}
    />

这里我想将文本的颜色更改为 false 时的绿色或 true 时的红色 如何在不出错的情况下实际应用颜色?

一种方法是将样式对象改为函数。该函数将采用一个用于定义文本颜色的参数:

import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants'



// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';


const MyText = ({isLive}) => {
  return (
      <Text style={styles.text(isLive)}>
        Change code in the editor and watch it change on your phone! Save to get a shareable url.
      </Text>
  )
}
export default function App() {
  return (
    <View style={styles.container}>
      <MyText isLive />
      <MyText />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  text: (isLive) => ({
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: isLive ? 'green' : 'black'
  }),
});

你也可以将条件传递给样式属性

const MyText = ({isLive}) => {
  return (
      <Text style={{color: isLive? 'green' : 'red' }}>
        Your text
      </Text>
  )
}