javascript - 更改 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:类型无效 - 需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入
这里有什么问题?
解决方案
我相信这是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
&&
Boolean
String
将其粘贴到浏览器控制台时可以看到它:
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"
推荐阅读
- tensorflow - 检查 TensorFlow 安装是否支持 XLA
- java - 我无法使用 Dagger2 将我的课程注入我的 ViewHolder
- javascript - 从 html 和 javascript 中的下拉选择中调用函数
- deployment - .NET CORE 通过命令行发布文件夹配置文件不起作用
- c++ - 如何在 Windows 上使用 Visual Studio 2017 连接到 C++ 中的 sqlite 数据库?
- url - URL.getText() 是否总是关闭连接?
- c# - 打印 ac# 对象列表
- java - 无法使用 tomcat 9 在 Intellij 中热交换 html 文件
- c# - 关于正则表达式的并行 foreach 问题
- c# - 动态生成的 MSIL 中奇怪的 DateTime ToString 行为