美文网首页
2018-01-29

2018-01-29

作者: NOTEBOOK2 | 来源:发表于2018-01-29 10:16 被阅读0次

1 将转换方法写在Input里面不具有耦合性,分离最好


屏幕快照 2018-01-29 10.13.04.png
  const changeHandler = 
  onChange?
  ({ target: { name, value } }: React.ChangeEvent<HTMLInputElement>) =>
     onChange(formatter(value, format), name)
    : null

周五的做法在input里面写format方法,不好

                <Input
                 name="price"
                 label="Price"
                 value={(price: number) => `$${price}`}
                 format="toCurrency"
                 required
                />

400错误,price不是一个数字

export const currency = {
  formatter: (input: any) => {
    let price = input.replace(/[^0-9]/, "")
    console.log(price)
    price = typeof price === "number" ? price : parseFloat(price)
    console.log(price)
    return Number.isNaN(price) ? "" : `$${price}`
  },
  getter: (input: string) => {
    input.replace(/$/g, "")
    return parseFloat(input)
  }
}

any => string
string => number

export const currency = {
  formatter: (input: any) => {
    const price =  parseFloat(input.replace(/^[0-9]\./, ""))
    return `$${price.toFixed(1)}`
  },
  getter: (input: any) => {
    const price = input.replace("$", "")
    return price
  }
}

最终的

export const currency = {
formatter: (input: any) => {
 const price = parseFloat(input.replace(/^[0-9]\./, ""))
 return `$${price.toFixed(1)}`
},
getter: (input: string) => {
 const price = input.replace("$", "")
 return price
},
}

export const toFloat = {
formatter: (input: any) => {
 const price = parseFloat(input.replace(/^[0-9]\./, ""))
 return `$${price.toFixed(1)}`
},
getter: (input: string) => {
 return input
},
}

export const toInteger = {
formatter: (input: any) => {
 const price = parseFloat(input.replace(/^[0-9]\./, ""))
 return `$${price.toFixed()}`
},
getter: (input: string) => {
 return input
},
}

相关文章

网友评论

      本文标题:2018-01-29

      本文链接:https://www.haomeiwen.com/subject/gztxzxtx.html