反应如何使用Textfield Material-UI中的图标和TypeScript

2022-02-22 00:00:00 reactjs css typescript material-ui formik

我已经使用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,因为<FieldAttributes<{}>>不接受它。如何定义FieldAttributes的新属性或修复此问题?


解决方案

使用文本字段属性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>
    )
  }}
/>


参考:

  • MUITextField Props API:inputProps,startAdornment,endAdornment

  • MUIInputInputAdornment Props API

  • 在线演示:https://stackblitz.com/edit/gzlbzm

相关文章