【问题标题】:React how to use icon inside Textfield Material-UI with TypeScript反应如何使用 TypeScript 在 Textfield Material-UI 中使用图标
【发布时间】:2020-07-27 16:07:03
【问题描述】:

我设计了一个使用 TypeScript Material UI 和 Formik 进行验证的表单。我希望在我的文本字段区域中出现一个材质 UI 图标,这是我的代码:


import React from 'react'
import { Formik, Form, FieldAttributes,useField} from 'formik'
import { TextField } from '@material-ui/core'
import CalendarTodayIcon from '@material-ui/icons/CalendarToday'
import * as yup from 'yup'
import './MainInfo.css'

const MyTextField: React.FC<FieldAttributes<{}>> = ({
  placeholder,type,className,style,
  ...props
}) => {
  const [field, meta] = useField<{}>(props);
  const errorText = meta.error && meta.touched ? meta.error : "";
  return (
    <div className='container'>
    <TextField
    placeholder={placeholder}
    className={className}
    style={style}
    type={type}
    {...field}
    helperText={errorText}
    error={!!errorText}
    id="outlined-basic" 
    variant="outlined"
  />
    </div>
  );
};

export function MainInfo() {

    return (
      <div>
        <Formik
          validateOnChange={true} validationSchema={validationSchema} initialValues={{ Title: '', ActivationDate: '', ExpirationDate: '', DirectManager: '', HRBP: '' }} onSubmit={(data) => {
            console.log(data)
          }}
        >
          {({values, errors}) => (
            <Form id='my-form' >
              <div>
                <label className='label'>عنوان</label>
                <div >            
                  <MyTextField style={{width:'60%'}}  placeholder='طراح' name='Title' type='input' />
                </div>
                  ...
              </div>
            </Form>
          )}
        </Formik>
      </div>
    )
}

但问题是我无法添加新的 Icon 属性或 InputProp,因为 &lt;FieldAttributes&lt;{}&gt;&gt; 不接受它。如何为 FieldAttributes 定义新属性或解决此问题?

【问题讨论】:

  • TextField 最终是一个&lt;input&gt; 元素,它实际上没有包含图标的选项。你想解释一下你到底需要什么吗?

标签: css reactjs typescript material-ui formik


【解决方案1】:

使用 TextField Props InputProps 自定义输入字段

并使用startAdornmentendAdornment自定义前缀/后缀

最后在InputAdornment里面使用图标就好了

import { TextField, InputAdornment } from "@material-ui/core";
import ExpandLess from "@material-ui/icons/ExpandLess";
import ExpandMore from "@material-ui/icons/ExpandMore";

<TextField
  id="standard-basic"
  label="Standard"
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <ExpandLess />
      </InputAdornment>
    ),
    endAdornment: (
      <InputAdornment position="end">
        <ExpandMore />
      </InputAdornment>
    )
  }}
/>


参考:

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2018-11-22
    • 2020-07-09
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多