简体   繁体   English

将本机设置样式反应为状态

[英]React Native set style as State

I want to use backgroundColor of style1 as a state, and change it in the function change() .我想使用style1 backgroundColor作为状态,并在函数change()更改它。
How can I access style1 ?如何访问style1

My point is to call the function change from another function, making the button change its color to yellow, then change it's colour to blue again after sometime.我的观点是从另一个函数调用函数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',
  },

});

You can give an array to style prop.你可以给一个数组来风格道具。 So you can put any other styles from another sources.因此,您可以放置​​来自其他来源的任何其他样式。

First you should declare a default value for your backgroundColor state:首先,您应该为 backgroundColor 状态声明一个默认值:

this.state = {
    backgroundColor: 'blue'
}

then set it's state in function as normal string state:然后将其状态设置为正常字符串状态:

this.setState({backgroundColor: 'yellow'});

and finally, use it in style prop:最后,在 style 道具中使用它:

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



If you want to use an object, instead of string as a state:如果要使用对象而不是字符串作为状态:

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',
  },

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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