reactjs - 当我记录mixedCategory is firstName [object Object] lastName时,如何在字符串中插入图标
问题描述
state = { icon: , }
loadAllCategories = async () =>
{
const{icon} = this.state;
firstCategory ="Electronic Devices";
lastCategory = "Phone"; mixedCategory =firstCategory+ icon + lastCategory;
};
解决方案
您需要返回一个 jsx 值,如下所示,对于包装,您可以使用React.Fragments
let mixedCategory = (
<>
{firstCategory} {icon} {lastCategory}
</>
);
代码
import React, { Component } from "react";
import ReactDOM from "react-dom";
const Icon = () => {
return (
<svg height="100" width="100">
<circle
cx="50"
cy="50"
r="40"
stroke="black"
stroke-width="3"
fill="red"
/>
Sorry, your browser does not support inline SVG.
</svg>
);
};
class App extends Component {
state = { icon: <Icon />, mixedValue: null };
loadAllCategories = () => {
const { icon } = this.state;
let firstCategory = "Electronic Devices";
let lastCategory = "Phone";
let mixedCategory = (
<>
{firstCategory} {icon} {lastCategory}
</>
);
this.setState({
mixedValue: mixedCategory
});
};
render() {
return (
<>
<button onClick={this.loadAllCategories}>Click here</button>
{this.state.mixedValue && this.state.mixedValue}
</>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
请参阅codepen中的工作示例
@更新
如使用 FontAwesomIcon 的评论中所述
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { library } from "@fortawesome/fontawesome-svg-core";
import { fab } from "@fortawesome/free-brands-svg-icons";
import { faInfo, faCoffee } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
library.add(fab, faInfo, faCoffee);
class App extends Component {
state = { icon: <FontAwesomeIcon icon="info" />, mixedValue: null };
loadAllCategories = () => {
const { icon } = this.state;
let firstCategory = "Electronic Devices";
let lastCategory = "Phone";
let mixedCategory = (
<>
{firstCategory} {icon} {lastCategory}
</>
);
this.setState({
mixedValue: mixedCategory
});
};
render() {
return (
<>
<button onClick={this.loadAllCategories}>Click here</button>
{this.state.mixedValue && this.state.mixedValue}
</>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
推荐阅读
- android - 将图像发送到 PHP 服务器时,android.content.ContentResolver.openInputStream 出现 NullPointer 异常
- css - 将选择器圆圈的颜色更改为最佳 jQuery 库中的滑块范围
- javascript - NG-STYLE 的两种方式绑定不工作在角度
- python - Python:BeautifulSoup 如何进入子类
- ios - sleep(1) 或 sleepForTimeInterval 1 需要超过 1 秒才能唤醒
- javascript - Jquery 仅在我在任何行上设置断点时运行,或者不会运行
- c# - 使用第一个/最早日期返回多条记录
- ios - AVMutableComposition 旋转视频文件
- excel - 条件格式,A和B的值之差大于2.5
- python - 使用 random.randint() 从列表中按索引绘制元素时出现索引错误