首页 > 解决方案 > 内联 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>
      )}
    </>
  );
};

标签: reactjstypescriptreact-hooksmaterial-uijsx

解决方案


推荐阅读