简体   繁体   English

如何在反应中单击按钮时获取输入字段值?

[英]how to get input field value on button click in react?

Could you please tell me how to get input field value on button click in react , I am using react hooks .I want to get first name and lastname value on button click.你能告诉我如何在反应中点击按钮时获取输入字段值吗,我正在使用反应钩子。我想在按钮点击时获取first namelastname值。 I already pass name attribute in my function component.我已经在我的函数组件中传递了name属性。

Here is my code这是我的代码

import React, { Component, useState } from 'react';
import { render } from 'react-dom';

export default function InputField({name,label}) {
  const [state, setState] = useState('')
  return (
    <div>
     <label>{label}</label>
      <input type="text" 
      value={state} 
      name={name}
      onChange={(e) => setState(e.target.value)} />

      {state}
    </div>
  );

}

Use <form> tag with useRef hook使用带有useRef钩子的<form>标签

Wrap your <InputField> tags with an html <form> tag and put a react ref on the later.用 html <form>标签包裹你的<InputField>标签,然后在后面放置一个 react ref Like this:像这样:

import React, { Component, useRef } from 'react'
import { render } from 'react-dom'

import InputField from './inputfield'

import './style.css'

function App () {
  const nameForm = useRef(null)

  const handleClickEvent = () => {
     const form = nameForm.current
     alert(`${form['firstname'].value} ${form['lastname'].value}`)
  }

  return (
    <div>
      <form ref={nameForm}>
       <InputField label={'first name'} name={'firstname'}/>
       <InputField label={'last name'} name={'lastname'}/>
      </form>
      <button onClick={handleClickEvent}>gett value</button>
    </div>
  )
}

render(<App />, document.getElementById('root'))

Working example: https://stackblitz.com/edit/react-shtnxj工作示例: https : //stackblitz.com/edit/react-shtnxj

You could always lift up the state in parent component.您始终可以在父组件中提升状态。 codeSandbox link代码沙盒链接

Parent Component父组件

import React from "react";
import ReactDOM from "react-dom";
import ChildComponent from "./Child";

const { useState } = React;

function App() {
  const [first_name, setFirstName] = useState("");
  const [last_name, setLastName] = useState("");
  const handleFirstNameChange = ({ target }) => {
    setFirstName(target.value);
  };
  const handleLastNameChange = ({ target }) => {
    setLastName(target.value);
  };
  const handleClick = () => {
    console.log(first_name);
    console.log(last_name);
  };
  return (
    <div className="App">
      <ChildComponent
        label="first name"
        onChange={handleFirstNameChange}
        value={first_name}
      />
      <ChildComponent
        label="last name"
        onChange={handleLastNameChange}
        value={last_name}
      />
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Child Component子组件

import React from "react";

const ChildComponent = ({ label, onChange, value, name }) => {
  return (
    <div>
      <label>{label}</label>
      <input type="text" value={value} name={name} onChange={onChange} />
    </div>
  );
};

export default ChildComponent;

You could always combine onChange handler for first name and last name.您始终可以为名字和姓氏组合 onChange 处理程序。

Hope that helps!!!希望有帮助!!!

A good solution is to move the state from InputField component into index:一个好的解决方案是将状态从 InputField 组件移动到索引中:

    const [F_name, setF_name] = useState('')
    const [L_name, setL_name] = useState('')

now you should pass state value and event handler to InputField to change the state when input is changed:现在您应该将状态值和事件处理程序传递给 InputField 以在输入更改时更改状态:

 <InputField label={'first name'} name={'firstname'} value={F_name} changed={(name) => setF_name(name)}/>

In Your InputField field: edit it to be like:在您的 InputField 字段中:将其编辑为:

   <input type="text" 
      value={value} 
      name={name}
      onChange={(e) => changed(e.target.value)} />

See Working Demo Here 在此处查看工作演示

The Easiest Way For Me is useRef对我来说最简单的方法是useRef

With useRef it's pretty simple.使用useRef非常简单。 Just add ref name and then submit.只需添加ref名称,然后提交。

const email = useRef(null);

function submitForm(e){
 e.preventDefault();
 
 console.log(email.current.value);
}

return (
 <div>
  <form onSubmit={submitForm}>
   <input type="text" ref={email} />
   <button>Submit</button>
  </form>
 </div>
)

 import React, { useRef } from 'react' const ViewDetail = () => { const textFirstName = useRef(null) const onChange = e => { console.log(textFirstName.current.state.value) } return <Input maxLength={30} ref={textFirstName} placeholder="Nombre" onChange=onChange} /> }

well one simple(but not necessarily recommended) way is to provide an id or a ref like this in index.js一种简单(但不一定推荐)的方法是在 index.js 中提供一个 id 或一个像这样的引用

<InputField label={'first name'} name={'firstname'} id={"ip1"}/>
<InputField label={'last name'} name={'lastname'} id={"ip2"}/>

and in your inputfield.js pass the id props to the input fields like this并在您的 inputfield.js 中将 id 道具传递给这样的输入字段

<input type="text" 
      value={state} 
      name={name}
      onChange={(e) => setState(e.target.value)} 
      id= {id}/>

Now you can call them in the onClick of the button like this in index.js现在您可以在 index.js 中像这样在按钮的 onClick 中调用它们

const handleClickEvent = ()=>{
  alert(document.getElementById("ip1").value);
  }

The second, more preferable way is to set the state variable in index.js第二种更可取的方法是在 index.js 中设置状态变量

function App() {
  const [stateIp1, setStateIp1] = useState('');
  const [stateIp2, setStateIp2] = useState('');
  const handleClickEvent = ()=>{
  alert(stateIp1);
  }
  return (
    <div>
      <InputField label={'first name'} state={stateIp1} setState={setStateIp1} name={'firstname'} id={"ip1"}/>
        <InputField label={'last name'}state={stateIp2} setState={setStateIp2} name={'lastname'} id={"ip2"}/>
        <button 
          onClick={handleClickEvent}

        >Get value</button>
    </div>
  );

}

Now your inputfield.js becomes现在你的 inputfield.js 变成

export default function InputField({name,label,id,setState,state}) {

  return (
    <div>
     <label>{label}</label>
      <input type="text" 
      value={state} 
      name={name}
      onChange={(e) => setState(e.target.value)} id= {id}/>
    </div>
  );

I can think of these approaches -我可以想到这些方法-

  • You can pull the state up to the parent component.您可以将状态拉到父组件。

App.js应用程序.js

const [user, setUser] = useState('');

return (
 <Inputfield setValue={setUser} value={user} />
);

InputField.js输入字段.js

<input value={props.value}  onChange={(e) => setValue(e.target.value)} />

  • You can use ref to access indiviual element value.您可以使用ref访问单个元素值。

  • If you have data distributed across multiple components you can also make use of Context API如果您的数据分布在多个组件中,您还可以使用Context API

Hope this helps!希望这可以帮助!

Do let me know if you need more info on any of the option.如果您需要有关任何选项的更多信息,请告诉我。 Thanks!谢谢!

You should do the react hooks work on your index and pass the value and the onChange function to your InputField component.您应该在索引上执行 react hooks 并将值和 onChange 函数传递给您的 InputField 组件。

//index page
import React, { Component, useState } from 'react';
import { render } from 'react-dom';
import InputField from './inputfield';
import './style.css';

function App() {
  const [firstname, setFirstName] = useState('');
  const [lastname, setLastName] = useState('');
  const handleClickEvent = ()=>{
    setFirstName('Will');
    setLastName('smith');
  }

  return (
    <div>
      <InputField
        label={'first name'}
        name={'firstname'}
        value={firstname}
        onChange={setFirstName}
      />
      <InputField
        label={'last name'}
        name={'lastname'}
        value={lastname}
        onChange={setLastName}
      />
      <button 
        onClick={handleClickEvent}

      >Get value</button>
    </div>
  );

}

render(<App />, document.getElementById('root'));

// input field

import React, { Component, useState } from 'react';
import { render } from 'react-dom';

export default function InputField({name,label, value, onChange}) {
  return (
    <div>
     <label>{label}</label>
      <input type="text" 
      value={value} 
      name={name}
      onChange={(e) => onChange(e.target.value)} />

      {value}
    </div>
  );

}

While keeping the majority of your structure the same, I think the simplest and most React solution is to use forwardRef() which in a nut-shell let's us communicate between then parent-component and child-components.在保持大部分结构相同的同时,我认为最简单和最 React 的解决方案是使用forwardRef()forwardRef() ,让我们在父组件和子组件之间进行通信。

See working sandbox .请参阅工作沙箱

App.js应用程序.js

import React, { useRef } from "react";
import InputField from "./InputField";
import ReactDOM from "react-dom";

function App() {
  const handleClickEvent = () => {
    if (firstName.current && lastName.current) {
      console.log(`firstName: ${firstName.current.value}`);
      console.log(`lastName: ${lastName.current.value}`);
    }
  };

  const firstName = useRef(null);
  const lastName = useRef(null);

  return (
    <div>
      <InputField ref={firstName} label={"first name"} name={"firstname"} />
      <InputField ref={lastName} label={"last name"} name={"lastname"} />
      <button onClick={handleClickEvent}>Get value</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

InputField.js输入字段.js

import React, { useState } from "react";

const InputField = React.forwardRef((props, ref) => {
  const [state, setState] = useState("");
  return (
    <div>
      <label>{props.label}</label>
      <input
        ref={ref}
        type="text"
        value={state}
        name={props.name}
        onChange={e => setState(e.target.value)}
      />

      {state}
    </div>
  );
});

export default InputField;

Notice that with this structure, you are not required to pass in any state updating function as props to the InputField component.请注意,使用此结构,您不需要将任何状态更新函数作为props传递给InputField组件。 The value that you enter into each input will be strictly maintained by the individual component.您在每个输入中输入的值将由各个组件严格维护。 It is independent from the Parent , and therefore makes it much more reusable.它独立于Parent ,因此使其更具可重用性。

The refs we created allow us to tap into specific elements of the InputField so we extract the desired values.我们创建的 refs 允许我们利用InputField特定元素,以便我们提取所需的值。 In this case, we can get first-name and last-name through the handleClickEvent function.在这种情况下,我们可以通过handleClickEvent函数获取名字和姓氏。

you can achieve this doing the following:您可以执行以下操作来实现此目的:

import React, { Component, useState } from 'react';
import { render } from 'react-dom';

export default function InputField({name,label}) {
  const [state, setState] = useState('');
  const handleChange = e => {
    setState(e.target.value);
  };

  return (
    <div>
     <label>{label}</label>
      <input
        type="text" 
        value={state} 
        name={name}
        onChange={handleChange}
      />
      {state}
    </div>
  );
}

Hopes this helps.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM