我正在尝试创建一个 React 组件,该组件在按下时在黑色和白色之间切换徽标。我想在组件中加入更多功能,但changeLogo()
控制台.log甚至不会显示在调试器中。
任何帮助/提示表示赞赏!
反应原生:0.39.2反应: ^15.4.2
import React, { Component } from 'react';
import { View, Image } from 'react-native';
export default class TestButton extends Component {
constructor(props) {
super(props);
this.state = { uri: require('./icons/logo_white.png') }
}
changeLogo() {
console.log('state changed!');
this.setState({
uri: require('./icons/logo_black.png')
});
}
render() {
return (
<View
style={styles.container}
>
<Image
source={this.state.uri}
style={styles.logoStyle}
onPress={this.changeLogo}
/>
</View>
);
}
}
const styles = {
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'blue',
},
logoStyle: {
width: 200,
height: 200,
marginLeft: 10,
marginRight: 5,
alignSelf: 'center',
},
};
onPress
道具不适用于图像组件。您需要像这样使用TouchableHighgo组件包装它:
import { View, Image, TouchableHighlight } from 'react-native';
...
<TouchableHighlight onPress={() => this.changeLogo()}>
<Image
source={this.state.uri}
style={styles.logoStyle}
/>
</TouchableHighlight>