我正在尝试创建一个React组件,该组件在按下时会在黑色和白色之间切换徽标.我想在组件中加入更多功能,但是changeLogo()console.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道具不适用于Image组件.您需要使用TouchableHighlight组件将其包装起来,如下所示:
import { View, Image, TouchableHighlight } from 'react-native';
...
<TouchableHighlight onPress={() => this.changeLogo()}>
<Image
source={this.state.uri}
style={styles.logoStyle}
/>
</TouchableHighlight>