[英]When I log mixedCategory is firstName[object Object]lastName, How to insert icon inside a string
state = { icon: , }
loadAllCategories = async () =>
{
const{icon} = this.state;
firstCategory ="Electronic Devices";
lastCategory = "Phone"; mixedCategory =firstCategory+ icon + lastCategory;
};
You need to return as a jsx value as shown below, for wrapping you can use React.Fragments您需要作为 jsx 值返回,如下所示,对于包装,您可以使用React.Fragments
let mixedCategory = (
<>
{firstCategory} {icon} {lastCategory}
</>
);
Code代码
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);
see the working example in the codepen请参阅codepen 中的工作示例
@Update @更新
as mentioned in the comments using FontAwesomIcon如使用 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.