业务组件调用:
<Input
name="price"
label="Price"
required
formatter={currency.formatter}
getter={currency.parser}
/>
自定义组件编写:
const Input: React.SFC<Props<any> & WithStyles> = ({
type,
name,
...
formatter = (value: any) => value,
parser = (value: any) => value,
}) => {
const changeHandler = onChange
? ({ target: { name, value } }: React.ChangeEvent<HTMLInputElement>) => onChange(parser(value), name)
: null
value = value === null || value === undefined ? "" : formatter(value)
const input = (
<div className={classes.wrapper}>
<input
ref={ctrlRef}
type={type}
...
disabled={disabled || isStatic}
/>
<div className={classes.validMsg}>{validMsg}</div>
</div>
)
return label ? (
<label className={cs(className)}>
<div className={classes.label}>
{label}
{required && <span className={classes.required}>*</span>}
</div>
{input}
</label>
) : (
input
)
}
transformer 方法:
export const currency = {
formatter: (input: any) => {
const price = parseFloat(input)
return Number.isNaN(price) ? "" : `$${price.toFixed(1)}`
},
parser: (input: string) => {
const price = input.replace("$", "")
return parseFloat(price)
},
}
重点:
interface Props<T = any> {
...
transformer?: { formatter: (input: T) => T; parser?: (input: T) => T }
// formatter?: (input: T) => string
// parser?: (input: string) => T
}
网友评论