我使用表情符号 API,我得到了这样的表情符号 unicode
U+1F425
,以便能够在 jsx 中显示表情符号。我必须将 U+1F425
替换为 \u{1F425}
。基本上我只需要从 api 获取 1F425
。
表情符号.jsx
import React, { useEffect, useState } from "react";
import Sidebar from "../../Sidebar/Sidebar";
import "./Emoji.css";
const Emoji = ({ isAuth, setIsAuth }) => {
const [type, setType] = useState([]);
const getEmoji = () => {
fetch("https://emojihub.herokuapp.com/api/all/group_animal_bird")
.then((resp) => resp.json())
.then((dat) => (console.log(dat), setType(dat)));
};
useEffect(() => {
getEmoji();
console.log(type);
}, []);
return (
<>
{type.map((emo) => (
<>
<h6>{emo.name}</h6>
<span>{emo.unicode}</span> // This Not
<span>{"\u{1F985}"}</span> //This works
</>
))}
</>
);
};
export default Emoji;
感谢您的帮助!
表情符号只不过是字符。 您必须将该代码转换为十六进制,然后将该十六进制代码转换为字符串。
const res = '1F425';
// Convert your string to hex code
const resHex = +`0x${res}`;
// Convert Hex to string
String.fromCodePoint(resHex); // You can render this directly
-> 您可以使用函数替换接收到的数据中的格式,然后再将其渲染到 jsx 中。
-> 在您的情况下,您可以尝试拆分字符串,将十六进制部分转换为 unicode 点,然后以所需的格式重新构造。
-> 在 midify 代码中,convertUnicode 函数采用 Unicode 字符串(U+1F425) 并以 (\u{iF425} 格式返回。然后在 getEmoji 函数中,每个 emo 对象都映射为用 Unicode 字符替换 unicode 属性。
import React, { useEffect, useState } from "react";
import Sidebar from "../../Sidebar/Sidebar";
import "./Emoji.css";
const Emoji = ({ isAuth, setIsAuth }) => {
const [type, setType] = useState([]);
const convertUnicode = (unicode) => {
// Split the Unicode string and get the hexadecimal part
const hexString = unicode.split("U+")[1];
// Convert hexadecimal to decimal
const decimalCode = parseInt(hexString, 16);
// Convert decimal code to Unicode character
return String.fromCodePoint(decimalCode);
};
const getEmoji = () => {
fetch("https://emojihub.herokuapp.com/api/all/group_animal_bird")
.then((resp) => resp.json())
.then((dat) => setType(dat.map(emo => ({ ...emo, unicode: convertUnicode(emo.unicode) }))));
};
useEffect(() => {
getEmoji();
}, []);
return (
<>
{type.map((emo, index) => (
<div key={index}>
<h6>{emo.name}</h6>
{/* Render the converted Unicode */}
<span>{emo.unicode}</span>
</div>
))}
</>
);
};
export default Emoji;
<span dangerouslySetInnerHTML={{ __html: emo.htmlCode[0] }}></span>
对从 API 获取的表情符号代码进行切片应该可以...
import React, { useEffect, useState } from "react";
import Sidebar from "../../Sidebar/Sidebar";
import "./Emoji.css";
const Emoji = ({ isAuth, setIsAuth }) => {
const [type, setType] = useState([]);
const getEmoji = () => {
fetch("https://emojihub.herokuapp.com/api/all/group_animal_bird")
.then((resp) => resp.json())
.then((dat) => (console.log(dat), setType(dat)));
};
useEffect(() => {
getEmoji();
console.log(type);
}, []);
return (
<>
{type.map((emo) => (
<>
<h6>{emo.name}</h6>
<span>{"\u{" + emo.unicode.slice(2) + "}"}</span> //This should work now.
</>
))}
</>
);
};
export default Emoji;
...你可以尝试一下。