[英]Change svg color : React.createElement: type is invalid — expected a string
I have a section I would like on click to change the color of SVG color,我有一个部分我想点击更改 SVG 颜色的颜色,
Here is my solution so far到目前为止,这是我的解决方案
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;
Unfortunatelly iam getting the following error不幸的是,我收到以下错误
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports
What is wrong here?这里有什么问题?
I believe it's the tab
variable declaration.我相信这是tab
变量声明。
Try:尝试:
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;
It's very difficult to really know because I can only see part of the source code – so, my best guess is that on initial render, the tab
variable is not defined (yet), and therefore is undefined
.很难真正知道,因为我只能看到部分源代码——所以,我最好的猜测是在初始渲染时, tab
变量没有定义(还),因此是undefined
。
When you use short-hand logic like this: tab === "downloadoptions" && 'active-tab'
, JavaScript returns the value false
when the part before the &&
is falsey.当您使用这样的简写逻辑时: tab === "downloadoptions" && 'active-tab'
,当&&
之前的部分为 false 时,JavaScript 返回值false
。 This is a Boolean
value, where React is expecting a String
.这是一个Boolean
值,其中 React 需要一个String
。
You can see it when you paste this into your browser console:将其粘贴到浏览器控制台时可以看到它:
let tab; // this sets the variable, but it is still "undefined"
console.info(tab === "downloadoptions" && 'active-tab'); // returns: false
It is therefore better to use a Ternary operator that will always return a string.因此,最好使用始终返回字符串的三元运算符。
Like so:像这样:
let tab; // this sets the variable, but it is still "undefined"
console.info(tab && tab === "downloadoptions" ? 'active-tab' : 'nothing'); // returns: "nothing"
Hope this clears things up.希望这可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.