添加后缀,后跟用户输入材料ui TextField [英] Add suffix follow by user input material ui TextField

查看:89
本文介绍了添加后缀,后跟用户输入材料ui TextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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}

/>

推荐答案

我认为装饰不是解决此问题的最佳方法.相反,您应该查看与3rd集成文档中的第三方输入库示例.

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.

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

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;

这篇关于添加后缀,后跟用户输入材料ui TextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆