在反应本机样式表中使用变量将无法识别该变量

Mat*_*zcz 4 javascript reactjs react-native react-native-stylesheet

我将颜色作为 props.color 导入到我的功能组件中,并将其设置为状态“tagColor”。当我在样式表中使用 tagColor 作为值来设置背景颜色时,我收到错误“找不到变量 tagColor”

如何在样式表中使用变量?

const Tag = (props) => {
  
  const [tagColor, setColor] = useState(props.color)

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.tag} title='tag'>
           
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    alignItems: "center",
    justifyContent: "center",
    height: 25,
    display: 'flex'
  },
  tag: {
    backgroundColor: tagColor,  
}
});

export default Tag;
Run Code Online (Sandbox Code Playgroud)

Ron*_* B. 7

嗯,它当然不认识tagColor,它在不同的范围内。注意tagColor是在函数组件的范围内,而StyleSheet是不同的范围。

解决这个问题的一种方法是将 直接传递backgroundColorstyleprop,如下所示:

<TouchableOpacity style={{backgroundColor: tagColor}} title="tag">
Run Code Online (Sandbox Code Playgroud)

tag另一种方法是将类定义StyleSheet为接收颜色并返回样式的函数,例如:

const styles = StyleSheet.create({
  container: {
    ...
  },
  tag: tagColor => ({
    backgroundColor: tagColor,  
})
});
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

<TouchableOpacity style={styles.tag(tagColor)} title="tag">
Run Code Online (Sandbox Code Playgroud)

如果您除了 之外没有更多样式,我会选择第一种方式backgroundColor。如果您需要更多样式,请使用第二种方法。