我在项目中使用了手风琴折叠反应本色,但是我尝试根据Qr扫描动态更改每种折叠颜色。我无法显示每次塌陷的颜色。您能帮帮我吗?
答案 0 :(得分:0)
您可以使用this.setState
在构造函数中设置初始背景色
this.state = {
backgroundColor: randomHex()
}
在渲染功能中,将样式道具更改为:
[styles.container, {backgroundColor: this.state.backgroundColor}]
然后onClick添加
this.setState({backgroundColor: randomHex()});
显示完整代码
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native';
let randomHex = () => {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
export default class randomBackground extends Component {
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this);
this.state = {
backgroundColor: randomHex()
};
}
onClick() {
console.log('clicked ');
this.setState({backgroundColor: randomHex()});
}
render() {
return (
<TouchableHighlight onPress={ this.onClick } style={[styles.container, {backgroundColor: this.state.backgroundColor}]}>
<View>
<Text style={styles.instructions}>
Tap to change the background
</Text>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: randomHex()
},
instructions: {
color: "white"
}
});
AppRegistry.registerComponent('randomBackground', () => randomBackground);