添加后缀,后跟用户输入材料ui TextField

时间:2019-02-15 03:05:11

标签: javascript reactjs material-ui

我想创建一个TextField元素,该元素在用户输入后跟输入装饰时具有值。

是否可以在值后添加%符号而不是输入的末尾?

当前百分比符号(%)在用户键入之前在输入的开始处,并且如果有值,将转到输入的结束。

<TextField
{...defaultProps}
InputProps={{
    startAdornment: this.state.percentage ? (
        <span />
    ) : (
        <InputAdornment position='start'>%</InputAdornment>
    ),
    endAdornment: this.state.percentage ? (
        <InputAdornment position='end'>%</InputAdornment>
    ) : (
        <span />
    ),
    classes: defaultInputClasses
}}
error={this.state.percentageError ? true : false}
fullWidth
helperText={this.state.percentageError ? 'percentage must be between 1-100' : ''}
id='percentage'
label='percentage'
margin='normal'
name='percentage'
onChange={this.handleChange}
value={this.state.percentage}

/>

初始状态

initial

用户键入时的当前状态

keyIn

预期

expected

1 个答案:

答案 0 :(得分:1)

我认为装饰不是解决此问题的最佳方法。相反,您应该查看文档中的Formatted Inputs示例。

这是该演示的修改版,其中使用“ react-number-format”包添加了%后缀:

import React from "react";
import NumberFormat from "react-number-format";
import PropTypes from "prop-types";
import TextField from "@material-ui/core/TextField";

function NumberFormatCustom(props) {
  const { inputRef, onChange, ...other } = props;

  return (
    <NumberFormat
      {...other}
      getInputRef={inputRef}
      onValueChange={values => {
        onChange({
          target: {
            value: values.value
          }
        });
      }}
      thousandSeparator
      suffix="%"
    />
  );
}

NumberFormatCustom.propTypes = {
  inputRef: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired
};

class FormattedInputs extends React.Component {
  state = {
    numberformat: "90"
  };

  handleChange = name => event => {
    this.setState({
      [name]: event.target.value
    });
  };

  render() {
    const { numberformat } = this.state;

    return (
      <TextField
        label="react-number-format"
        value={numberformat}
        onChange={this.handleChange("numberformat")}
        id="formatted-numberformat-input"
        InputProps={{
          inputComponent: NumberFormatCustom
        }}
      />
    );
  }
}

export default FormattedInputs;

Edit Material demo