1. 程式人生 > 程式設計 >在react專案中使用antd的form元件,動態設定input框的值

在react專案中使用antd的form元件,動態設定input框的值

問題:

建立賬號時,輸入賬號後不搜尋直接儲存,提示查詢後,再點搜尋就不能搜尋這個賬號了

在react專案中使用antd的form元件,動態設定input框的值

原因:

點選儲存之後,對錶單進行了驗證,導致之後請求的資料無法在更新到input框中,也就是說即使在state中有值,也不會更新initialValue值,就導致搜尋後的值不能正確填入input中,表單也就提交不了。

解決辦法:

不使用initialValue設定動態更新的值,而是使用 this.props.form.setFieldValue({name:data}); 用於動態更新值,就可以解決了。

if (result.code===0) {
 if (result.data) {
  this.props.form.setFieldsValue({name:result.data});
 }
}

ps:

還有一個問題,如果輸入了賬號進行搜尋後匹配了name,也填入了input框中。但是又修改了賬號,然後直接提交,就會導致賬號和name不匹配,也就是name是存在的,但就不是對應的賬號了。會導致儲存之後,如果正確的賬號和name已經存在,資料庫出現數據儲存問題。

解決:

給賬號輸入的Input框新增onChange事件,來觸發如果有改變就清空name框,防止錯誤提交

change = (event) => {
 this.props.form.setFieldsValue({name:''});
}

記錄一下

補充知識:重新封裝Antd Input元件,解決中文輸入問題

我就廢話不多說了,大家還是直接看程式碼吧~

import React,{ useState,useEffect } from 'react'
import { Input } from 'antd'
function BaseHOC(key) {
 return function(props) {
 const { defaultValue,value,onChange } = props
 const hasValue = props.hasOwnProperty('value')
 // 使用者切換到底是顯示 value 還是 input
 // 不能直接用 isOnComposition 原因是,這個值發生變化不會觸發重新渲染
 // 不能只使用 flag 原因是,setFlag 是非同步的
 const [flag,setFlag] = useState(false)
 // 非中文輸入時候顯示 value。中文輸入的時候顯示 input
 const [input,setInput] = useState(hasValue ? value : defaultValue)
 useEffect(
 function() {
 if (hasValue && input !== value) {
  setInput(value)
 }
 },[value]
 )
 let isOnComposition = false
 function handleChange(e) {
 setInput(e.target.value)
 if (isOnComposition) return
 onChange && onChange(e)
 }
 function handleComposition(e) {
 if ('compositionend' === e.type) {
 isOnComposition = false
 handleChange(e)
 } else {
 isOnComposition = true
 }
 if (flag !== isOnComposition) {
 setFlag(isOnComposition)
 }
 }
 let Component = Input
 if (key) {
 Component = Input[key]
 }
 return (
 <Component
 {...props}
 value={hasValue && !flag ? value : input}
 onCompositionStart={handleComposition}
 onCompositionUpdate={handleComposition}
 onCompositionEnd={handleComposition}
 onChange={handleChange}
 />
 )
 }
}

const Component = function(props) {
 return BaseHOC()(props)
}

Component.Search = function(props) {
 return BaseHOC('Search')(props)
}

Component.TextArea = function(props) {
 return BaseHOC('TextArea')(props)
}

Component.Password = Input.Password
Component.Group = Input.Group
export default Component

以上這篇在react專案中使用antd的form元件,動態設定input框的值就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。