单击时更改图像,再次单击React Native时再次更改为上一图像

时间:2017-08-28 21:36:01

标签: image reactjs react-native state

我需要在点击图像时更改图像,如果单击图像则需要再次更改图像我需要返回到之前的状态,当我再次点击图像时,本机代码是:

constructor (props) {
    super(props);
    this.state = {
      toggleCollapse: false,
      selectedUnit: null,
     uri: require('../resources/icons/circle.png') 
    };
     _onPress = () => {
    this.props.onPressItem(this.props.item, this.props.index);
    this._renderLessons(this.props.item, this.props.index);
    this.setState({
            toggleCollapse: !this.state.toggleCollapse,
            uri: require('../resources/loader.gif')
        });
  }

2 个答案:

答案 0 :(得分:0)

我是怎么做到的:

images = {
    'first_image': require('../resources/icons/circle.png'),
    'second_image': require('../resources/loader.gif'),
};
class Example extends Component {
constructor (props) {
    super(props);
    this.state = {
        toggleCollapse: false,
        selectedUnit: null,
     };
}
_onPress = () => {
    .....
    this.setState({
        toggleCollapse: !this.state.toggleCollapse
    });
}
render() {
    return (
        ....
        <Image source={this.state.toggleCollapse ? images.first_image : images.second_image} />
        ....
    )
}
}

答案 1 :(得分:0)

有两种状态可以切换值

constructor (props) {
    super(props);
    this.state = {
    toggleCollapse: false,
    selectedUnit: null,
    next = require('../resources/icons/circle.png'),
    uri: require('../resources/icons/circle.png') ,
    temp_store: ''
};
 _onPress = () => {
        this.props.onPressItem(this.props.item, this.props.index);
        this._renderLessons(this.props.item, this.props.index);
        this.setState({
            toggleCollapse: !this.state.toggleCollapse,
            temp_store: this.state.uri,
            uri: this.state.next,
            next: this.state.temp_store
       });
  }

基本上,将当前uri存储在临时状态,将uri更改为next状态,然后将之前的uri(temp_store内部)设置为下一个状态。