将道具发送到数字格式 - Material UI TextField

Mai*_*rez 4 reactjs material-ui

我想创建一个 TextField 元素来处理数字字段。我想动态处理这个组件,这样它不仅可以帮助我管理信用卡格式、电话等。我使用 react-number-format 库的方式与 Material-UI 示例相同。我试图通过道具“前缀”和“格式”发送而没有有利的结果。我想知道我应该如何发送这些属性,如果我有办法的话。提前致谢 !

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

  return (
    <NumberFormat
      {...other}
      getInputRef={inputRef}
      onValueChange={values => {
        onChange({
          target: {
            value: values.value
          }
        });
      }}     
      thousandSeparator={","}
      decimalSeparator={"."}
      isNumericString
      prefix={props.prefix} //"$"      
    />
  );
}

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

class NumberTextField extends Component {
  state = {
    numberformat: this.props.value
  };

  handleChange = event => {
    const targetField = this.props.name;
    const targetValue = event.target.value;
    this.setState({
      ...this.state,
      numberformat: targetValue
    });
    this.props.updateCurrentUserFieldsOnChange(targetField, targetValue);
  };

  render() {
    const { fullWidth, label, name, readOnly, prefix } = this.props;
    return (
      <Fragment>
        <TextField
          fullWidth={fullWidth ? fullWidth : true}
          label={label ? label : "react-number-format"}
          name={name}
          value={this.state.numberformat}
          onChange={this.handleChange}          
          InputProps={{
            inputComponent: NumberFormatCustom,
            readOnly: Boolean(readOnly),
            prefix: prefix                        
          }}
        />
      </Fragment>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*son 16

您必须使用 customInput 道具,这将允许您集成 material-ui 的样式。您还可以传递几个道具,以便能够随心所欲地控制面具。另外,如果您想要前缀,只需使用前缀道具。千位分隔符是一个布尔值,但默认情况下数字用逗号分隔,如果你喜欢空格,你只需要像我的例子一样添加它

  import NumberFormat from 'react-number-format';

  import TextField from 'material-ui/TextField';

      <NumberFormat
        {...props}
        value={value}
        name={name}
        mask={mask}
        customInput={TextField}
        prefix={'$'}
        format={format || null}
        type="text"
        thousandSeparator={thousandSeparator ? ' ' : null}
        onValueChange={({ value: v }) => onChange({ target: { name, value: v } })}
      />

Run Code Online (Sandbox Code Playgroud)