【问题标题】:Access to style property and change it访问样式属性并更改它
【发布时间】:2020-05-01 17:45:21
【问题描述】:

我是 React-Native 的新手。假设我有一个 styleSheet 包含绿色按钮的样式:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff', 
  },
  greenB:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,    
    backgroundColor:'green',    
  }, ........

由于某种原因,我需要在我的代码中更改该颜色。

render(){
....
const {container, greenB}=styles; //Not sure, how else can I define greenB?

greenB.backgroundColor='black';

return (
      <View style={styles.container}>
          <View style={styles.greenB} >
          ....

如何从 greenB 访问 backgroundColor 并更改它? 我收到一个 TypeError “尝试分配给只读属性”, 这是合理的原因样式是一个常量。 尝试阅读有关状态管理的信息,但不确定在这种情况下如何使用它。

【问题讨论】:

标签: react-native


【解决方案1】:

React Native 的 StyleSheet.create 用于更好的性能和干净的代码,它缓存样式 id 以减少通过桥的数据量,这就是为什么你不能改变它但是只用它。

但是有很多解决方案,您可以使用简单的 javascript 对象并根据需要更改值。

例如:-

let Styles= {
            Text:{ 
                 color:'blue'
                 }
          }
Styles.Text.color= 'green'


<Text style={Styles.Text} > </Text>


此外,对于动态样式,我建议使用状态而不是变量。

【讨论】:

    猜你喜欢
    • 2019-09-13
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2021-08-05
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多