我正在使用 React 创建一个应用程序,我想使用 FontAwesome 图标将它们包含到输入占位符中,这样它看起来就像
<input type="text" placeholder="[here should be the user icon] Username" />
我怎样才能做到这一点?我用过
" Username"
它只显示一个正方形而不是一个图标。也许我忘记了什么?
最佳答案
尝试将您的图标包含为 InputAddon
而不是强制它进入你的占位符。您可以通过几种方式做到这一点。我会推荐下面列出的两个。
方法一:Bootstrap
您可以安装 bootstrap 并使用 input-group-prepend
或 input-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>
)
}
这将需要您安装
bootstrap
和 react-icons
. bootstrap
安装将允许您使用那些 classNames
和 react-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/