Javascript 将本机集样式作为状态进行反应

Javascript 将本机集样式作为状态进行反应,javascript,reactjs,react-native,react-native-android,state,Javascript,Reactjs,React Native,React Native Android,State,我想使用style1的backgroundColor作为状态,并在函数change()中更改它 如何访问style1 我的意思是从另一个函数调用函数change,使按钮将其颜色更改为黄色,然后在一段时间后再次将其颜色更改为蓝色 export default class App extends Component{ constructor (props){ super(props); this.state = { //style1.backgroundColour

我想使用
style1
backgroundColor
作为状态,并在函数
change()
中更改它
如何访问
style1

我的意思是从另一个函数调用函数
change
,使按钮将其颜色更改为黄色,然后在一段时间后再次将其颜色更改为蓝色

export default class App extends Component{ 
  constructor (props){
    super(props);
    this.state = {
      //style1.backgroundColour: blue  //? Can't 
    }
    this.change=this.change.bind(this)
  }

  change() {
    this.setState({ style1.backgroundColour: yellow }) //?
  }

  render(){
    return (
      <View style={styles.style1} > </View>

    );
  }
}

const styles = StyleSheet.create({

  style1:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,    
    backgroundColor:'blue',
  },

});
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
//样式1.背景颜色:蓝色/?不能
}
this.change=this.change.bind(this)
}
更改(){
this.setState({style1.backgroundcolor:yellow})/?
}
render(){
返回(
);
}
}
const styles=StyleSheet.create({
样式1:{
填充:5,
身高:80,
宽度:80,
边界半径:160,
背景颜色:'蓝色',
},
});

您可以为样式道具提供一个数组。因此,您可以从其他来源放置任何其他样式

首先,您应该为backgroundColor状态声明一个默认值:

this.state = {
    backgroundColor: 'blue'
}
然后将其在函数中的状态设置为正常字符串状态:

this.setState({backgroundColor: 'yellow'});
最后,在样式道具中使用它:

style={[styles.style1, {backgroundColor: this.state.backgroundColor}]}


如果要使用对象而不是字符串作为状态:

export default class App extends Component{ 
  constructor (props){
    super(props);
    this.state = {
      style1: {
        backgroundColor: 'blue'
      }
    }
    this.change=this.change.bind(this)
  }

  change() {
    this.setState({ style1: {...this.state.style1, backgroundColor: 'yellow' } })
  }

  render(){
    return (
      <View style={[styles.style1, this.state.style1]}> </View>

    );
  }
}

const styles = StyleSheet.create({

  style1:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,    
    backgroundColor:'blue',
  },

});
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
样式1:{
背景颜色:“蓝色”
}
}
this.change=this.change.bind(this)
}
更改(){
this.setState({style1:{…this.state.style1,backgroundColor:'yellow'}})
}
render(){
返回(
);
}
}
const styles=StyleSheet.create({
样式1:{
填充:5,
身高:80,
宽度:80,
边界半径:160,
背景颜色:'蓝色',
},
});

我遇到了一个错误不变冲突:文本字符串必须在文本组件中呈现。我试图删除它,并将其替换为:{this.state.backgroundColor}{this.state.backgroundColor},只是想看看它是否改变了状态,它确实改变了。但是为什么我会出现这个错误呢?很抱歉,我的回答是:D,这个错误意味着你在视图组件中使用了文本,等等,或者是语法错误。很可能是您不小心按了一个键。我刚刚把我的答案复制粘贴并测试了一下。它工作得很好