首页 > 解决方案 > 更改 svg 颜色:React.createElement: type is invalid -- 需要一个字符串

问题描述

我有一个部分我想单击以更改 SVG 颜色的颜色。

到目前为止,这是我的解决方案:

    import { ReactComponent as DownloadSVG } from 'assets/images/share_download.svg';
        .......
    
    const Demo = () => {
    
        return (
         <div className={`download-options ${tab ==='downloadoptions' && 'active-tab'}`}>
           <span style={{ backgroundColor: isBlack ? '#262626' : '#F3F3F3'}} className="download_icon" onClick={handleDownloadTabClick}>
                        <DownloadSVG style={{ fill: isBlack ? '#fff' : '#262626'}} />
            </span>
          <span className="download_title media-text">DOWNLOAD</span>
         </div>
    )
 }
export default Demo;

不幸的是,我收到以下错误:

React.createElement:类型无效 - 需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入

这里有什么问题?

标签: javascripthtmlcssreactjssvg

解决方案


相信这是tab变量声明。

尝试:

import { ReactComponent as DownloadSVG } from "assets/images/share_download.svg";

const Demo = () => {
  return (
    <div
      className={`download-options ${
        tab && tab === "downloadoptions" ? "active-tab" : ""
      }`}
    >
      <span
        style={{ backgroundColor: isBlack ? "#262626" : "#F3F3F3" }}
        className="download_icon"
        onClick={handleDownloadTabClick}
      >
        <DownloadSVG style={{ fill: isBlack ? "#fff" : "#262626" }} />
      </span>
      <span className="download_title media-text">DOWNLOAD</span>
    </div>
  );
};

export default Demo;

为什么这有效

很难真正知道,因为我只能看到部分源代码——所以,我最好的猜测是在初始渲染时,tab变量没有定义(还),因此是undefined.

当您使用这样的简写逻辑时: ,当 之前的部分为假时tab === "downloadoptions" && 'active-tab',JavaScript 会返回该值 。这是一个值,React 期望一个.false&&BooleanString

将其粘贴到浏览器控制台时可以看到它:

let tab; // this sets the variable, but it is still "undefined"
console.info(tab === "downloadoptions" && 'active-tab'); // returns: false

因此,最好使用始终返回字符串的三元运算符。

像这样:

let tab; // this sets the variable, but it is still "undefined"
console.info(tab && tab === "downloadoptions" ? 'active-tab' : 'nothing'); // returns: "nothing"

推荐阅读