Add suffix follow by user input material ui TextField

有些话、适合烂在心里 提交于 2020-04-14 07:37:13

问题


I want to create TextField element that has value when user key in followed by Input Adornment.

Is it possible to add % sign after value instead of end of input ?

Currently percentage sign(%) is at start of input before user key in and will go to end of input if there is value.

<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 state

initial

Current state when user key in

keyIn

Expected

expected


回答1:


I think adornments are not the best approach for this problem. Instead you should look at the Integration with 3rd party input libraries example in the documentation.

Here is a modified version of the demo using the "react-number-format" package to add a % suffix:

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;



来源:https://stackoverflow.com/questions/54702150/add-suffix-follow-by-user-input-material-ui-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!