反应如何使用Textfield Material-UI中的图标和TypeScript [英] React how to use icon inside Textfield Material-UI with TypeScript
本文介绍了反应如何使用Textfield Material-UI中的图标和TypeScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用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自定义输入字段
并使用startAdornment
、endAdornment
自定义前缀/后缀
最后在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
这篇关于反应如何使用Textfield Material-UI中的图标和TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文