强制以大写形式输入表单 - onChange 和 React Hooks

tom*_*zub 0 reactjs redux react-hooks

我想强制以大写形式输入表单。

我使用了一种onChange方法和 React Hooks,但它不起作用,我不知道为什么......这是非常基本的,但我是 React 初学者。

我在更高的组件上导入了我的 Redux 存储: props name -> "facture"

import React, { useState } from 'react'
import { Col, Row } from 'mdmrc/lib/components/grid'
import { Button } from 'mdmrc/lib/components/button'
import { Form } from 'mdmrc/lib/components/form'
import { Input } from 'mdmrc/lib/components/input'
import { useTranslation } from 'react-i18next'

/**
 * composant de mise à jour des données de la facture
 */
export const UpdateForm = ({ classes, onSubmit, facture }) => {
  // ajout de la traduction
  const { t } = useTranslation()

  const [codePaysValue, setCodePaysValue] = useState(
    facture.codePays ? facture.codePays : ''
  )

  const handleChange = e => {
    const value = e.target.value.toUpperCase()
    setCodePaysValue(value)
  }

  /**
   * Controle de surface du formulaire d'update
   */
  const validationOptions = {
    some code here...
  }

  return (
    <Col span={12} className={classes.updateForm}>
      <Form
        id="update-form"
        onSubmit={onSubmit}
        validationOptions={validationOptions}
        defaultValues={{
          codePays: codePaysValue ? codePaysValue : '',
        }}
      >
        <Row>
          <Col span={8}>
            <label>{t('updateForm.codePays')}</label>
          </Col>
          <Col span={16}>
            <Input
              type="text"
              maxLength={2}
              name="codePays"
              id="codePays"
              onChange={handleChange}
            />
          </Col>
        </Row>
        <Button type="primary" style={{ width: '100%' }} htmlType="submit">
          {t('updateForm.enregistrer')}
        </Button>
      </Form>
    </Col>
Run Code Online (Sandbox Code Playgroud)

没有控制台错误。但是如果我不使用大写字母,我的代码总是小写的。

tar*_*ugh 6

在您的代码中,您没有使用值字段或某些其他属性作为输入值。请参阅所用库组件prop type的定义。Input

<Input
  type="text"
  maxLength={2}
  name="codePays"
  id="codePays"
  onChange={handleChange}
  value={codePaysValue}
/>
Run Code Online (Sandbox Code Playgroud)

供参考 - 使用钩子获取大写输入值的简单示例。

import React, { useState } from "react";
import ReactDOM from "react-dom";


function App() {
  const [value, setValue] = useState('')
  const changeHandler = ({ target }) => {
    setValue(target.value.toUpperCase())
  }
  return (
    <div className="App">
      <input type='text' value={value} onChange={changeHandler}></input>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Run Code Online (Sandbox Code Playgroud)

希望有帮助!


tom*_*zub 5

在这里,我使用的是我公司创建的自制库(基于 Ant Design)并且位于 FORM.item 包装器中。所以我刚刚发现了问题:我必须使用 normalize 道具。例子:

<Form>
    <Input
        type="text"
        maxLength={2}
        name="codePays"
        id="codePays"
        normalize={value => (value || '').toUpperCase()}
    />
</Form>
Run Code Online (Sandbox Code Playgroud)