我正在使用 react-dropzone来允许用户上传个人资料照片. 我这样定义自定义CSS: const dropzoneStyle = { width: `200px`, height: `200px`, backgroundColor: `#1DA1F2`,}; 在渲染DropZone输入的方法中,我可以检测它
我这样定义自定义CSS:
const dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
};
在渲染DropZone输入的方法中,我可以检测它们是否是在用户选择要上载的图像后填充的文件预览.
我想要做的是,如果file.preview存在,则将file.preview发送到dropzoneStyle,以便将背景图像添加到CSS中.
const renderDropzoneInput = (field) => {
const files = field.input.value;
let dropzoneRef;
if (files[0]) {
console.log(files[0].preview)
}
return (
<div>
<Dropzone
name={field.name}
ref={(node) => { dropzoneRef = node; }}
accept="image/jpeg, image/png"
style={dropzoneStyle}
>
如何使用React将文件[0] .preview传递给样式dropzoneStyle?
谢谢
假设文件[0] .preview返回文件(图像)URL,您应该能够设置新样式并将其传递给Dropzone组件.这些方面的东西:
const renderDropzoneInput = (field) => {
const files = field.input.value;
let dropzoneRef;
render() {
let dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
};
if (files[0]) {
dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
backgroundImage: `url(${files[0].preview})`,
// or to use a fixed background image
// backgroundImage: `url(/path/to/static/preview.png)`,
backgroundPosition: `center center`,
backgroundRepeat: `no-repeat`
};
}
return (
<Dropzone
name={field.name}
ref={(node) => { dropzoneRef = node; }}
accept="image/jpeg, image/png"
style={dropzoneStyle}
/>
)
}
}
可以使用扩展运算符来稍微干掉此代码,其中:
let dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
};
if (files[0]) {
dropzoneStyle = {
...dropzoneStyle,
backgroundImage: `url(/path/to/static/preview.png)`,
backgroundPosition: `center center`,
backgroundRepeat: `no-repeat`
};
}
