zoukankan      html  css  js  c++  java
  • React后台管理手动封装图片上传组件

    分为两个文件夹,index.js(逻辑文件)    styled.js(样式文件)

    index.js文件,编写完成之后在对应的地方引入即可

    import React from "react"
    import { UploadContainer } from "./styled"
    import { Icon ,message} from "antd"
    import { fetch as fetchPro } from "whatwg-fetch"
    class Upload extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                imgUrl: ""
            }
            if (this.props.value) {
                this.state.imgUrl = this.props.value
            }
        }
        render() {
            let { imgUrl } = this.state
            return (
                <UploadContainer>
                    <input type="file" onChange={this.handleUpdate.bind(this)} ref="files" />
                    <div className="imgContent">
                        {imgUrl ? <img src={imgUrl} /> : <Icon type="plus" style={{ fontSize: 26 }} />}
                    </div>
                </UploadContainer>
            )
        }
        async handleUpdate() {
            let fileImg = this.refs.files.files[0];

            let formData = new FormData()

            formData.append("filesImg", fileImg)//第一个参数为后端规定字段,第二个参数时需要上传的图片

            let data = await fetchPro("/ajax/upload/files", {
                method: "post",
                body: formData
            }).then(res => res.json())//第一个参数为地址,第二个参数为配置项
            
            if(data.data.urlPath){
                this.setState({
                    imgUrl:data.data.urlPath
                })
            }else{
                message.error(data.data.info)
            }
        }
    }


    export default Upload

    styled.js文件

    import styled from "styled-components"
    
    export const UploadContainer = styled.div`
        110px;
        height:110px;
        border:1px dashed #ccc;
        position:relative;
        input{
            opacity:0;
            110px;
            height:100%;
            position:absolute;
            left:0;
            top:0;
            z-index:2;
        }
        .imgContent{
            padding:5px;
            100%;
            height:100%;
            position:absolute;
            left:0;
            top:0;
            display:flex;
            justify-content:center;
            align-items:center;
            img{
                100%;
                height:100%;
            }
        }
    `
  • 相关阅读:
    JavaScript模态对话框类
    事件模块的演变(1)
    html5中可通过document.head获取head元素
    How to search for just a specific file type in Visual Studio code?
    What do 'lazy' and 'greedy' mean in the context of regular expressions?
    正则非获取匹配 Lookahead and Lookbehind ZeroLength Assertions
    regex length 正则长度问题
    Inversion of Control vs Dependency Injection
    How to return View with QueryString in ASP.NET MVC 2?
    今天才发现Google Reader
  • 原文地址:https://www.cnblogs.com/Bree/p/12016167.html
Copyright © 2011-2022 走看看