javascript - 单击对象中最后一张图像之后的图像时,如何切换图像?

标签 javascript reactjs algorithm debugging

我想在 imagesPath 对象中切换图像。截至目前,您可以成功切换 plusminus

换句话说,在点击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)。如果我正确理解了你的描述,你想实现像轮播这样的东西,所以我准备了两个例子。一个在数组上,第二个在对象上。

https://codesandbox.io/s/w0pvoqv7m5 - 对象

https://codesandbox.io/s/ojprx25q9y - 数组

关于javascript - 单击对象中最后一张图像之后的图像时,如何切换图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333539/

相关文章:

javascript - 如何将数组传递给 map ?句法

react-native - 如何重定向到 React Native 中的页面?

javascript - 开 Jest 没有找到所有测试

java - 使用 java 遍历 CIDR 中的所有 IP 地址

algorithm - 如何使用 A* 算法找到最佳的三条路线

javascript - jQuery ajax 在 chrome 中工作,但在 IE 9 中不起作用

javascript - 编写一个退出 while 循环的 exit 条件

javascript - 循环遍历 CSS 表格并对选定的单元格进行计数

javascript - 创建一个 React 组件

python - 对排序算法效率的困惑