我想在 imagesPath
对象中切换图像。截至目前,您可以成功切换 plus
和 minus
。
换句话说,在点击plus
图像时,minus
会切换,反之亦然。
在 updateObject()
方法中,我添加了一个键/值对,它添加了键 divide
和值 https://image.flaticon。 com/icons/png/128/43/43097.png
.
点击时如何到达divide
图像(plus
> minus
> divide
)随后,是否能够在点击过去 divide
时到达其他键/值?
我觉得我必须在 toggleImage()
方法中使用 this.setState(state => ({open: !state.open}));
进行调整但不确定如何。
import React, { Component } from 'react';
import './App.css';
const imagesPath = {
minus: "https://images.vexels.com/media/users/3/131484/isolated/preview/a432fa4062ed3d68771db7c1d65ee885-minus-inside-circle-icon-by-vexels.png",
plus: "https://cdn3.iconfinder.com/data/icons/glypho-generic-icons/64/plus-big-512.png"
};
console.log(imagesPath);
class App extends Component {
constructor(props) {
super(props);
this.state = {
open: true
};
this.updateObject = this.updateObject.bind(this);
}
toggleImage = () => {
this.setState(state => ({open: !state.open}));
};
updateObject = () => {
for (let key in imagesPath) {
key = "helloThere";
imagesPath[key] = "some new url";
}
imagesPath["divide"] = "https://image.flaticon.com/icons/png/128/43/43097.png";
};
getImageName = () => this.state.open ? 'plus' : 'minus';
render() {
const imageName = this.getImageName();
return (
<div className="App">
<img src={imagesPath[imageName]} onClick={this.toggleImage} style={{maxWidth: '50px'}}/>
{this.updateObject()}
</div>
);
}
}
export default App;
最佳答案
我认为您应该将图像路径存储在组件的 state
中,并避免在渲染中修改数据(在我的示例中,我将其移至 componentDidMount
)。如果我正确理解了你的描述,你想实现像轮播这样的东西,所以我准备了两个例子。一个在数组上,第二个在对象上。
关于javascript - 单击对象中最后一张图像之后的图像时,如何切换图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333539/