reactjs - 使用 React 的输入占位符中的 FontAwesome 图标

标签 reactjs font-awesome

我正在使用 React 创建一个应用程序,我想使用 FontAwesome 图标将它们包含到输入占位符中,这样它看起来就像

<input type="text" placeholder="[here should be the user icon] Username" />

我怎样才能做到这一点?我用过 "&#xF007; Username"它只显示一个正方形而不是一个图标。也许我忘记了什么?

最佳答案

尝试将您的图标包含为 InputAddon而不是强制它进入你的占位符。您可以通过几种方式做到这一点。我会推荐下面列出的两个。

方法一:Bootstrap

您可以安装 bootstrap 并使用 input-group-prependinput-group-append类并将您的图标放在那里。

例子:

    import { FaUserAlt } from 'react-icons/fa';

    render() {
      return (
        <div className="input-group mb-3">
          <div className="input-group-prepend">
            <i className="classes you have"><FaUserAlt /></i>
        </div>
        <input type="text" className="form-control" placeholder="Username" />
       </div>
     )
  }

这将需要您安装 bootstrapreact-icons . bootstrap安装将允许您使用那些 classNamesreact-icons安装将允许您使用 <FaUserAlt />作为一个组件而不是通过 CSS。安装 bootstrap使用:npm i bootstrap .安装 react-icons使用:npm i react-icons .

方法二:Reactstrap

您可以使用 reactstrap这本质上是用于 react 的 Bootstrap。这将要求您同时安装 reactstrap , react-icons , 和 bootstrap像这样:npm i reactstrap bootstrap react-icons .

示例:来自 reactstrap文档(略有改动)
import React from 'react';
import { InputGroup, InputGroupText, InputGroupAddon, Input } from 'reactstrap';
import { FaUserAlt } from 'react-icons/fa';
const Example = (props) => {
  return (
    <div>
      <InputGroup>
        <Input placeholder="Username" />
        <InputGroupAddon addonType="append">
          <FaUserAlt />
        </InputGroupAddon>
      </InputGroup>
    </div>
  );
};

export default Example;

替代方法

您可以简单地使用 CSS 执行上述操作。如果你只使用一次这个“图标占位符”,我会走这条路。但是,如果您在整个应用程序中始终如此,我认为研究上述两种方法可能是值得的。

希望这可以帮助遇到此问题的任何人。

关于reactjs - 使用 React 的输入占位符中的 FontAwesome 图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803798/

相关文章:

javascript - 从 React 中的 e.currentTarget 向上移动 DOM 树时,parentNode 为空

reactjs - 在react-dnd中找不到DragSource

html - 用 less/css 覆盖字体很棒的图标

javascript - 如何从 fontawesome-svg-core api 修改 icon().abstract.children[0].attributes?

css - 如何将图标附加到输入搜索?

javascript - 如何在基于 React 函数的 View 中进行 api 调用并填充渲染

oracle - 在生产中使用 Babel - 如何预编译脚本

javascript - 为什么我会收到此错误 - 'You are calling withTheme(Component) with an undefined component.' -React JS

jsp - Fontawesome图标不显示

css - 如何在不将其上传到元素的情况下使用 FontAwesome 字体图标?