Material-UI:如何在React中的输入字段中显示搜索图标?

29

我正在使用Material UI。 我想在输入框中显示搜索图标,如下图所示 enter image description here

我正在使用这个API

这里是我的代码

我能够显示TextField,但无法添加搜索图标。 请问如何添加?

 <TextField id="standard-bare" defaultValue="Bare" margin="normal" />
4个回答

63

你需要使用输入装饰

例如:


// imports
import IconButton from "@material-ui/core/IconButton";
import InputAdornment from "@material-ui/core/InputAdornment";
import SearchIcon from "@material-ui/icons/Search";

// render

<TextField
  label="With normal TextField"
  InputProps={{
    endAdornment: (
      <InputAdornment>
        <IconButton>
          <SearchIcon />
        </IconButton>
      </InputAdornment>
    )
  }}
/>

这里是一个演示:

const {
  TextField,
  InputAdornment,
  IconButton,
  SearchIcon,
  Icon
} = window['material-ui'];

class App extends React.Component {
  render() {
    return (
      <TextField
        label="With normal TextField"
        InputProps={{
          endAdornment: (
            <InputAdornment>
              <IconButton>
                <Icon>search</Icon>
              </IconButton>
            </InputAdornment>
          )
        }}
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@latest/umd/react-dom.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@material-ui/core/umd/material-ui.development.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

<div id="root"></div>


1
这里需要 IconButton 是为了什么?是为了使搜索图标可以点击或者其他什么原因吗? - Alex McMillan
1
@AlexMcMillan 是的。图标基本上是一个SVG元素,所以你需要将它放在一个按钮上。 - mehamasum

14

你只需导入 inputAdornment:

import InputAdornment from '@material-ui/core/InputAdornment';

并将 InputProps 添加到 textField 中,例如:

InputProps={{
  endAdornment: (
    <InputAdornment position="start">
      <SearchIcon />
    </InputAdornment>
   )
  }}

请查看附加的图片以了解所需解决方案的演示。

enter image description here


8

在我的情况下,我只使用了IconButton

import {  TextField, IconButton } from '@material-ui/core';

import { SearchOutlined } from '@material-ui/icons';

我的例子:

             <TextField
                fullWidth
                id="standard-bare"
                variant="outlined"
                defaultValue="How can we help"
                InputProps={{
                  endAdornment: (
                    <IconButton>
                      <SearchOutlined />
                    </IconButton>
                  ),
                }}
              />


           

enter image description here


0

你可以使用InputBase

<Box sx={{display:"flex",justifyContent:"space-between", border:1, borderRadius:4}}>

    <InputBase />

    <IconButton>
      <BiSearch />
    </IconButton>

 </Box>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接