加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 在React中,如何将动态变量传递给const CSS样式列表?

发布时间:2020-12-15 09:32:33 所属栏目:百科 来源:网络整理
导读:我正在使用 react-dropzone来允许用户上传个人资料照片. 我这样定义自定义CSS: const dropzoneStyle = { width: `200px`,height: `200px`,backgroundColor: `#1DA1F2`,}; 在渲染DropZone输入的方法中,我可以检测它们是否是在用户选择要上载的图像后填充的文
我正在使用 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}
      >

如何使用React将文件[0] .preview传递给样式dropzoneStyle?

谢谢

解决方法

假设文件[0] .preview返回文件(图像)URL,您应该能够设置新样式并将其传递给Dropzone组件.

这些方面的东西:

const renderDropzoneInput = (field) => {
  const files = field.input.value;
  let dropzoneRef;

  render() {
    let dropzoneStyle = {
      width: `200px`,};

    if (files[0]) {
      dropzoneStyle = {
        width: `200px`,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`,};

if (files[0]) {
  dropzoneStyle = {
    ...dropzoneStyle,backgroundImage: `url(/path/to/static/preview.png)`,backgroundRepeat: `no-repeat`
  };
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读