单击后更改图像,再次单击React Native时再次更改为上一图像
问题描述:
我需要在图像上单击时更改图像,如果单击图像时需要再次更改图像,如果再次单击图像时需要返回到先前状态在图像反应原生我的代码是:单击后更改图像,再次单击React Native时再次更改为上一图像
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')
});
}
答
在这里,我如何做到这一点:
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} />
....
)
}
}
答
有两种状态,开关值
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内部)成为下一个状态。
你的解释很棒:) – Andrew