首页 > 解决方案 > styled.input 中占位符左侧的图像反应

问题描述

我正在努力实现这个设计: goalimg

这就是我到目前为止所拥有的:currentimg

我需要在此输入中的占位符文本左侧显示搜索图标。我在 react javascript 中使用了一个样式化的输入组件。这是我输入的 CSS 样式:

const SearchBar = styled.input`
color: #000000;
margin-top: 20px;
background: #F2F2F7;
padding-left: 35.33px;
border-radius: 50px;
height: 30px;

border: 1px solid ${props => props.theme.gray2};
padding-top: 7px;
padding-bottom: 7px;
margin-left: 14px;
margin-right: 14px;
outline-width: 1px;
display: flex;
flex-direction: row;

`;

这是在 render() 方法中:

<SearchBar placeholder="Search Chats"></SearchBar>

如何将图像放置在占位符文本左侧的输入中?

标签: javascriptcssreactjsinputstyled-components

解决方案


在您的 index.html(或您将应用程序渲染到的任何位置)中添加到头部:

<head>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div id="app"></div>

在你的 React 文件中添加:

 <span className='search-bar'>
    <i className="fa fa-search" aria-hidden="true"></i>
    <input></input>
 </span>

在您的 Css 文件中添加:

.search-bar { 
  position: relative;
  input { padding: 12px; }
  .fa-search { 
    position: absolute; 
    padding: 12px;
    top: 2px; 
    left: 5px; 
    z-index: 1; 
  }
}

或者,代替填充,您可以使用

.fa-search { 
  position: absolute; 
  top: 2px; 
  left: 5px; 
  z-index: 1; 
}

调整顶部和左侧值以准确定位它。

加上输入的任何其他样式。

您可以在此处访问许多图标:链接


推荐阅读