问题
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
Current state when user key in
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