软件环境

  • macOS Big Sur 11.1
  • React 16.12.0
  • Ant Design 4.10.0

实际效果

现有一个需要,是上传文件,点击浏览文件按钮,选中文件后,在按钮的上方显示,上传的文件列表,如下图所示

以后成果

目前应用阿里的Ant UI组件库,应用其中的上传组件,官网提供的示例,如下图如示

本地应用后,如下图所示

如何能力实现,咱们须要的成果呢,Google了好多文章,找到了一种形式,就是重写itemRender办法,自定义文件列表的展现,应用这个办法,须要重写多个action。

起初查看公司前端人员写的代码,看到另一种解决办法。

次要应用两个Upload组件,第一个Upload组件次要是展现文件列表,第二个Upload组件是抉择文件上传的这个操作,不过,抉择文件后,把文件列表在下方展现暗藏起来。

showUploadList: false, //不显示上传的列表

把失去的文件列表,赋值给第一个Upload组件中,大略如下:

beforeUpload(file: any, fileList: any) {            setFileList(fileList); //设置文件列表            return false; //不要调用上传文件接口        },
<!--第一个Upload组件--><Upload fileList={fileList}></Upload>

局部代码如下:

 <StyleContent>    <StyleMainContent>        <Button onClick={btnOnClick} type="primary">关上上传</Button>        <Modal visible={isVisible} title="上传附件" footer={[]} closable>            <div style={{ border: '1px solid #ccc', height: 150, marginBottom: 10 }}>                <Upload fileList={fileList} onChange={onChange}></Upload>            </div>            <div style={{ textAlign: 'right' }}>                <Upload {...updateProps} ><Button type="primary">浏览文件</Button></Upload>                <Button style={{marginLeft:2}} onClick={() => { setIsVisible(false) }}>敞开</Button>            </div>        </Modal>    </StyleMainContent></StyleContent>
    const [isVisible, setIsVisible] = useState(false);    const [fileList, setFileList] = useState([]);    const btnOnClick = () => {        setIsVisible(true);    }    const updateProps = {        name: 'file',        beforeUpload(file: any, fileList: any) {            setFileList(fileList);            return false;        },        showUploadList: false,        styly: {            display: 'inline-block'        }    }    const onChange = ({ file, fileList }: { file: any; fileList: any }) => {        console.log(file, fileList);        setFileList(fileList);    };