【发布时间】:2020-09-19 09:34:13
【问题描述】:
我想制作具有自定义样式的输入类型文件,我隐藏输入并使用 css 设置标签样式。有两个问题:
- 我选择了文件,但未定义coverFileState(如果我删除css样式并选择文件,则一切正常)。
- 我想在标签内设置文件名,但它不起作用。我在 handleCoverChange 中使用 setCoverUploadText 设置文本,但没有效果。
如果您能帮我解决这个问题,我将不胜感激,谢谢!
const useStyles = makeStyles((theme) => ({
fileInput: {
marginBottom: '1em',
width: '0.1px',
height: '0.1px',
opacity: '0',
overflow: "hidden",
position: "absolute"
},
uploadLabel: {
fontSize: '1rem',
cursor: 'pointer',
color: "gray",
border: "1px solid gray"
}
}));
export default function AddingBook(props: ParamsProps) {
const classes = useStyles();
const coverFile = useRef(null);
const [coverFileState, setCoverFile] = useState<string | Blob>();
const [coverUploadText, setCoverUploadText] = useState("Upload cover photo *");
const handleSubmit = () => {
if (coverFileState === undefined) {
setImageErrorMsg("*Please add cover photo.");
return;
}
api.post('/image/add', JSON.stringify(REST))
.then(res => {
uploadCoverPhoto();
props.close();
}).catch(err => {
const errorMsg = APIServices.onError(err);
showErrorPopup(errorMsg);
})
};
const handleCoverChange = () => {
// @ts-ignore
setCoverFile(coverFile.current.files[0]);
// @ts-ignore
setCoverUploadText(coverFile.current.files[0].name)
};
return (
<>
<div>
<input
id="copy-file-upload"
type="file"
accept="image/*"
ref={coverFile}
onChange={handleCoverChange}
data-testid="inputFile"
className={classes.fileInput}
/>
<label className={classes.uploadLabel} htmlFor="copy-file-upload">{coverUploadText}</label>
</div>
</>
);
【问题讨论】:
标签: reactjs typescript jsx