我想使用backgroundColorstyle1作为状态,并在函数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',
  },

});

最佳答案

您可以给样式标签一个数组。因此,您可以从其他来源提供任何其他样式。

首先,您应该为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',
  },

});

08-18 12:17
查看更多