如何在不更改格式值的情况下在 <Input>如 <SearchInput>上使用“解析”?

问题描述

假设我有一个 <SearchInput>,我想在解析时将其转换为小写以发送到服务器进行查询

但是,我不希望 Input 反映同样的事情。我以为 parse 只更改发送服务器的数据,但它也反映了输入框(好像我也使用了 format)。

我可以使用 format 将其改回,但是……我什至如何在解析之前“返回”原始值?

例如:

<SearchInput
    source='lastNameLower'
    placeholder='Last Name'
    parse={ v => v && v.toLowerCase() }
/>

如果我输入“Foo”=> parse 成功发送foo(小写)到服务器。 但是,好像我也使用了 format=,输入值也发生了变化......那么我如何保持原始值并只为服务器解析?

解决方法

使用 SearchInput 作为受控组件

  • 创建状态以存储用户输入
  • 在用户输入时更新状态
  • 将输入的值设置为状态变量
  • 提交时,将输入转换为小写并提交

我不确定您的 SearchInput 组件是什么样子或它来自哪里,但下面是模型,哪些代码会给您一个想法。

const App = () => {

  const [searchInput,setSearchInput] = useState(""); //state for the search the user is inputting

  const onInput = (e) => {
    setSearchInput(e.target.value); //e.target.value is typical for html input,sometimes it will just be "value" if the SearchInput is from a package. You will need to look at the docs for this
  }

  //Lower case the input and submit
  const handleSubmit = () => {
    //convert the search input to a lowercase
    const submitVal = searchInput.toLowerCase();
    //call API endppoint 
    yourApi.call(submitVal).then(res => {
     //do what you wish with the results
    })
  }

  return (
    <div>
      <SearchInput
        source='lastNameLower'
        placeholder='Last Name'
        value={searchInput}
        onChange={onInput} 
      />
    <button onClick={handleSubmit}>submit</button>
   <div>
  )
}