在 JS 中反应表单输入值

React form input values in JS

我正在使用 NextJS 和 bulma CSS 创建一个简单的应用程序。我有以下表格:

const MyPage = () => {
const [firstName, setFirstName] = useState('')
const [secondName, setSecondName] = useState('')

const updateFirstName = event => {
    setFirstName(event.target.value)
}

const updateSecondName = event => {
    setSecondName(event.target.value)
}

const createUser = async() => {
   // Todo: perform some action with firstName and secondName
}

return (
<section className='mt-5'>
    <div className='container'>
        <div className='field'>
            <label className='label'>My Form</label>
            <div className='control'>
                <input onChange={updateFirstName} className='input' type='type' placeholder='Enter First Name'></input>
            </div>
        </div>
        <div className='field'>
            <div className='control'>
                <input onChange={updateSecondName} className='input' type='type' placeholder='Enter Second Name'></input>
            </div>
        </div>
        <button onClick={createUser} className='button is-primary'>Create</button>
    </div>
</section>
)
}
export default MyPage

我必须在每次输入更改时调用 updateFirstNameupdateSecondName。 我只想在 createUser() 函数调用中获取这些输入字段的值。请建议如何去做或任何其他更好的方法。我想消除 firstName 和 secondName 变量,并直接访问 createUser() 函数中输入的输入。

如果您不想要受控输入。您可以停止管理状态并使用普通 JS 以旧方式访问值。

确保在所有输入字段中添加名称属性。

function createUser() {
    
   const inputs = document.querySelectorAll(".field input")
   let data = {}
   inputs.forEach(input => {
      data[input.name] = input.value
   })
   /**
    This would yield you
    {
      'firstname': 'value',
      'secondName': 'value' 
    }
   **/
}

请如下所示更改您的输入字段:

 <input onChange={(e)=>createUser(e,'firstName')} className='input' type='type' placeholder='Enter First Name'></input>
 <input onChange={(e)=>createUser(e,'lastName')} className='input' type='type' placeholder='Enter First Name'></input>

然后在您的 createUser 函数中更新如下所示:

const createUser = (event, element) => {
   if(element==='firstName') {
      setFirstName(event.target.value)
   }

   if(element==='lastName') {
      setLastName(event.target.value)
   }
}

您可以尝试使用此 useRef() 挂钩,

const MyPage = () => {

const firstName = useRef();
const secondaName = useRef();

const createUser = async() => {
    
   // Todo: perform some action with firstName and secondName
   console.log(firstName.current.value, secondName.current.value)  // It will prints the value that is typed by the user in both the textfields
  
}

return (
<section className='mt-5'>
    <div className='container'>
        <div className='field'>
            <label className='label'>My Form</label>
            <div className='control'>
                <input ref={firstName} className='input' type='type' placeholder='Enter First Name'></input>
            </div>
        </div>
        <div className='field'>
            <div className='control'>
                <input ref={secondName} className='input' type='type' placeholder='Enter Second Name'></input>
            </div>
        </div>
        <button onClick={createUser} className='button is-primary'>Create</button>
    </div>
</section>
)
}
export default MyPage

你可以写一个处理函数

首先,您应该将所有变量添加到相同的状态。

  const [userInfo, setUserInfo] = useState({
    firstName: "",
    secondName: ""
  });

你应该给这样的输入命名。

  <input
  className="input"
  onChange={onChangeHandler}
  name="firstName" //name attribute must same your state variable
  placeholder="Enter First Name"
  />

  <input
  className="input"
  onChange={onChangeHandler}
  name="secondName" //name attribute must same your state variable
  placeholder="Enter Second Name"
  />

你的处理函数应该是这样的

  const onChangeHandler = (e) =>
    setUserInfo({ ...userInfo, [e.target.name]: e.target.value });

此函数获取您的输入值并设置同名的状态。

完整代码

export default function App() {
  const [userInfo, setUserInfo] = useState({
    firstName: "",
    secondName: ""
  });

  const onChangeHandler = (e) =>
    setUserInfo({ ...userInfo, [e.target.name]: e.target.value });

  const sendData = () => {
    console.log(userInfo);
  };

  return (
    <div className="App">
      <section className="mt-5">
        <div className="container">
          <div className="field">
            <label className="label">My Form</label>
            <div className="control">
              <input
                className="input"
                onChange={onChangeHandler}
                name="firstName"
                placeholder="Enter First Name"
              />
            </div>
          </div>
          <div className="field">
            <div className="control">
              <input
                className="input"
                onChange={onChangeHandler}
                name="secondName"
                placeholder="Enter Second Name"
              />
            </div>
          </div>
          <button onClick={sendData} className="button is-primary">
            Create
          </button>
        </div>
      </section>
    </div>
  );
}

https://codesandbox.io/s/gallant-pasteur-uglbri?file=/src/App.js:58-1264