reactjs - 内联 InputLabelProps 三元组
问题描述
我谦虚地问,当 foo 存在和 foo 不存在时,如何在不为所有 inputLabel 道具创建三元组的情况下构建它。在这种情况下 foo 是如果我们将 characterLimit 传递给我们的自定义文本字段组件。
这基本上是我想要的,但是对于多个道具:Reusable TextField in React
这是我的代码,有没有办法做这个条件内联而不是创建 inputLabelProps 的多个实例?
import React, {ChangeEvent, useState} from 'react';
import {TextFieldProps, TextField, makeStyles, Box, FormHelperText} from '@material-ui/core';
export interface SATextFieldProps {
hasWhiteFields?: boolean;
requiredError?: string | undefined;
showCharacterCount?: boolean;
characterLimit?: number;
}
const useStyles = makeStyles((theme: any) => ({
whiteTextField: {
background: theme.palette.common.white,
},
}));
export const SATextField = (props: TextFieldProps & SATextFieldProps) => {
const classes = useStyles();
const [characterCount, setCharacterCount] = useState<number>(0);
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
props.onChange && props.onChange(event);
props.showCharacterCount && setCharacterCount(event.target.value.length);
};
return (
<>
<TextField
{...props}
label={props.label}
id={props.id}
name={props.name}
className={props.className}
type="text"
variant="outlined"
fullWidth
inputRef={props.inputRef}
InputLabelProps={props.InputLabelProps}
inputProps={{...props.inputProps, props.characterLimit ? {maxLength: props.characterLimit} : undefined, ...{className: classes.whiteTextField}}}
error={props.error}
helperText={props.helperText}
autoComplete={props.autoComplete || 'none'}
onChange={onChange}
/>
{props.showCharacterCount && (
<Box position="relative" top="-20px" display="flex" justifyContent="flex-end">
<FormHelperText
error={props.error}
>{`${characterCount} / ${props.characterLimit}`}</FormHelperText>
</Box>
)}
</>
);
};
解决方案
推荐阅读
- mysql - 当表已经有数据在 NodeJS 中使用 Sequelize 时,如何添加列?
- xml - 如何使用 XSLT 将 XML 更改为 XML
- c# - 是否有 Visual Studio 扩展在下拉列表中显示 System.Drawing.Color 的颜色
- c# - 在 Linux 上部署 DotNet 核心应用程序时,存储日志和设置文件的 base/programdata 目录是什么?
- python-3.x - 在气流中组织 DAG 任务依赖项
- python - 试图找到唯一的子数组和子元素?
- laravel - Laravel 6.17 到更新版本升级问题 - 身份验证会话丢失
- python - Python pandas 将列索引转换为值
- angular - 使用 Angular 10 处理反应形式
- windows - 无法访问 Windows 的 GIT_SSH_COMMAND 中的身份文件