2018-01-30 一個(gè)自定義組件的流程

業(yè)務(wù)組件調(diào)用:

  <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)
  },
}

重點(diǎn):

interface Props<T = any> {
  ...
  transformer?: { formatter: (input: T) => T; parser?: (input: T) => T }
  // formatter?: (input: T) => string
  // parser?: (input: string) => T
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評(píng)論 25 709
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,719評(píng)論 18 399
  • 圖文/巴山雨 轉(zhuǎn)載請(qǐng)聯(lián)系作者授權(quán) 喜歡就來關(guān)注雨姐姐的專題我真的來畫畫,一起禪繞吧。 圖文/巴山雨 轉(zhuǎn)載請(qǐng)聯(lián)系作者...
    巴山雨閱讀 482評(píng)論 0 1
  • 4月23日是世界讀書日,我發(fā)現(xiàn)也漸漸地讀了一些書,數(shù)目不多,但卻愛上了這種放下包袱,安靜地品讀一本書的生活。不管是...
    嫌疑人西貝閱讀 627評(píng)論 5 8

友情鏈接更多精彩內(nèi)容