我在用着反应-dropzone https://github.com/okonet/react-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}
>
我怎样才能通过files[0].preview
到 React 的 dropzoneStyle 样式?
我通常只是将样式定义为返回样式对象的箭头函数,并传入样式所需的任何参数。有一种从箭头函数返回对象文字的简写符号非常适合此目的。
const style = () => ({});
请记住,如果使用简写,则仅使用三元运算符,否则您只需要显式地return
一个东西。
因此,根据您的风格:
const dropzoneStyle = (isPreview) => ({
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
backgroundImage: (isPreview) ? 'url(/path/to/image.jpg)' : 'none',
});
这添加了图像isPreview
是真的,但如果不是,则将其保留为空。
然后在您的组件中,调用样式所在的函数:
return (
<div>
<Dropzone
{...otherProps}
style={ dropzoneStyle(isPreview) }
>
</div>
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)