React-Native更改<img/>源与状态

时间:2017-01-16 01:39:20

标签: javascript reactjs react-native

我正在尝试创建一个React组件,可以在按下时切换黑色和白色之间的徽标。我想在未来的组件中加入更多功能,但changeLogo() console.log甚至不会显示在调试器中。

任何帮助/提示赞赏!

react-native: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',
  },
};

1 个答案:

答案 0 :(得分:3)

onPress道具不适用于Image组件。你需要用TouchableHighlight组件包装它,如下所示:

import { View, Image, TouchableHighlight } from 'react-native';

...

<TouchableHighlight onPress={() => this.changeLogo()}>
  <Image
    source={this.state.uri}
    style={styles.logoStyle}
  />
</TouchableHighlight> 
相关问题