基础前端

React 图片浏览器 rc-viewer

2019-08-20  本文已影响0人  CondorHero

要实现此功能,我们借助插件 @hanyk/rc-viewer 安装命令如下:

npm install @hanyk/rc-viewer

本地我借用 node 来模拟个接口,请求返回的结果之中就有图片链接。

import React, { Component } from 'react';
import axios from "axios";

export default class App extends Component {
    constructor(){
        super();
    }
    componentWillMount(){
        axios.get("http://192.168.2.250/car").then(data=>{
            const res = data.data;
            console.log(res);
        })
    }
    render() {
        return (
            <div>
                
            </div>
        )
    }
}

控制台返回的结果:



一共是十个数据:
现在使用这个插件把它给做成图片查载器。

import React, { Component } from 'react';
import axios from "axios";
import RcViewer from '@hanyk/rc-viewer';
import "../css/css.css";

export default class App extends Component {
    constructor(){
        super();
        this.state = {
            res : []
        }
    }
    componentWillMount(){
        axios.get("http://192.168.2.250/car").then(data=>{
            this.setState({
                res : data.data.results
            })
        })
    }
    render() {
        return (
            <div>
                <RcViewer options={{
                    url(image) {
                        return image.src.replace('carimages_small', 'carimages');
                    }
                }}>
                    <ul className = "cur" id="images">
                    <h1>点击查看大图</h1>
                    {
                        this.state.res.map((item,index) => <li key = {index}><img src={`http://192.168.2.250/images/carimages_small/${item.id}/view/${item.image}`} /></li>)
                    }
                    </ul>
                </RcViewer>
            </div>
        )
    }
}

options 里面是配置,所有的属性都在这里配置,现在放个 URL 函数,来回调这个 image 标签的 src 来进行替换。这里去掉 small 小图就变成大图了。

options={{
    url(image) {
        return image.src.replace('carimages_small', 'carimages');
    }
}}

如果是 Vue 可以使用下面这个插件:

v-viewer 插件使用教程:Vue图片浏览组件v-viewer,支持旋转、缩放、翻转等操作

上一篇 下一篇

猜你喜欢

热点阅读