我想在反应聊天应用程序的网页上显示表情符号。该计划是为用户提供一个可供选择的表情符号列表。如何使用“1F683”等代码并让它们在页面上显示表情符号?我需要支持 Chrome。
我可以使用CSS来显示表情符号。
<div className="smiley"></div>
.smiley:after {
content: "\01F683";
}
我还可以有一个图像列表,并将它们映射到代码,并为每个表情符号显示一个 img 元素。
还有其他方法吗?哪种方法是最好的方法?
我可能迟到了,但我需要通过同一个组件有条件地渲染不同的表情符号,所以对我来说最简单的方法是:
U+1F609
并将其用作十六进制数字 0x1F609
和代码中的 String.fromCodePoint
的字符串 — 请参阅下文。Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby jsx-a11y/accessible-emoji
:const Emoji = React.memo(({ className, label, symbol }) =>
<span className={className} role="img" aria-label={label}>
{String.fromCodePoint(symbol)}
</span>)
export default Emoji
那么你可以在其他地方使用它:
class MagnificentComponent extends PureComponent {
getEmojiConditionally = () => this.props.happy ? '0x1F60A' : '0x1F61E'
render = () =>
<SomeComponentWhereINeedEmoji>
<Emoji symbol={this.getEmojiConditionally(} />
</SomeComponentWhereINeedEmoji>
}
所有表情符号都按照表情符号备忘单中的格式进行了标准化,因此上面给出的示例 (
\01F683
) 映射到表情符号备忘单中的railway_car
。
使用这些标识符存储表情符号并稍后将其映射到实际表情符号可能是一个更好的主意,而不必担心对实际表情符号 (🚃) 本身进行编码,或者无法分辨/记住由Unicode 序列 (
\01F683
)。
如果您希望将此人类可读的标识符映射到实际的 Unicode 序列/符号本身,您有几个选项,以
railway_car
为例:
Twemoji Awesome 就像 Font Awesome,但带有 Twitter 表情符号。
然后您可以插入这样的表情符号,就像 Font Awesome 一样。
<i class="twa twa-railway-car"></i>
这将输出相应的SVG:
emoji-dictionary
的 npm 包,如果您希望使用默认浏览器的默认表情符号渲染器,它允许您将表情符号名称映射到 Unicode 字符。
用法将如下所示:
emoji.getUnicode("railway_car");
这将返回 🚃(它将在现代浏览器上显示/可能会在旧版浏览器上中断/等等)。
我们在 W3C 中有表情符号的 unicode。 其范围为{.十六进制
2600
-26FF
.}。
因此,您可以在没有 CSS 的情况下生成它。
查看下面的示例👇🏼
class Emoji extends React.Component {
render() {
const {title, code} = this.props;
return <span className="emoji" title={title}>{code}</span>
}
}
class App extends React.Component {
renderEmojis() {
const rangeEmojis = Array.from({length: 256}, (v, k) => (k + 9728).toString(16));
return rangeEmojis.map((code, index) => <Emoji code={unescape ('%u' + code)} title={"My code is :"+code} key={'emj'+index} />)
}
render() {
return (
<div>
{this.renderEmojis()}
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector('#chat'))
.emoji {
border: solid 1px #3e3e3e;
width: 50px;
height: 50px;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section id="chat" />
在 React 中使用表情符号的方法有很多种。使用 NPM 或不使用“span”标签也可以。
<span role="img" aria-label="arrow">➡️</span>
我发现这个简单易用。
Grinning face with big eyes
的反应代码:
<div>
{String.fromCodePoint('0x1f603')}
</div>
输出:
😃
完整表情符号列表,v15.0 - https://unicode.org/emoji/charts/full-emoji-list.html
--
将其放在这里,以防其他人偶然发现这篇文章来寻找我需要的东西。
<p>
After a lot of Googling and reading I just copy/pasted the emoji, it seems to work fine 🤷♂️.
</p>
为了获取表情符号,我前往 Discord 发送了我需要的表情符号,并将其复制/粘贴到我的代码中,然后它显示在屏幕上。
使用 Typescript
TS
或使用严格模式。
您无法将字符串参数传递给
String.fromCodePoint
,
因此参数必须是十六进制类型的数字,所以请尝试如下 -
String.fromCodePoint(parseInt('0x1f603', 16))
输出:😃