简体   繁体   中英

Change Image when clicked and again change to previous image when again clicked in React Native

I need to change the image when clicked on the image and again if the image is clicked i need to return to the previous state when again clicked on the image in react native my code is:

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')
        });
  }

Here how I do it:

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} />
        ....
    )
}
}

Have two states that switch values

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
       });
  }

Basically, store the current uri in a temporary state, change uri to the next state and then make the previous uri(inside temp_store) the next state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM