React/Next.js 如何在按钮点击时获取其他元素事件目标值

React/Next.js how to get other Element event target value on button click

我在 React 中有一个输入元素和一个按钮:

      <li><input type="text" placeholder="Enter new ID"></input>
      <button onClick={(e)=>this.saveKonfigElementHandler()}>Save</button></li>  

现在,当我在输入字段中输入一些值时,我想在单击按钮时将该值保存到某个数组中。 是否有可能以某种方式获得对该输入字段的引用(例如输入字段的 target.value)以在单击按钮时保存它?

或者我是否只需要使用 onChange 事件将当前输入值保存到某个变量中,然后当我单击按钮时,我将简单地检索该值以将其保存到某个数组中?也许那样会简单很多。

例如:

<input type="text" value={this.state.inputFieldText.join('')} onChange={(event) => this.textHandler(event)}></input>

在 textHandler 方法中,我会将输入字段中的目标值保存到 textHandler() 方法中的 Class 组件状态变量中。当我单击按钮时,我会检索该状态值并可以对其进行一些操作?

Is it somehow possible to get a reference to that input field (e.g. the target.value of the input field) to save it when clicking the button?

是的。

Or would I simply have to do it with an onChange event that saves the current input value into some Variable, and when I click the button, I will simply retrieve that value to save it into some array? Maybe that would be a lot simpler.

这将是一种稍微更 React 的方式。

您的 DOM-only 方法更 "uncontrolled"(请参阅 these docs 了解 controlled/uncontrolled 的含义)。你会这样做:

  1. 更改您的 onClick 以将 e 传递给处理程序:

    onClick={(e)=>this.saveKonfigElementHandler(e)}
    
  2. saveKonfigElementHandler中,使用e.target.previousElementSibling访问input:

    saveKonfigElementHandler(e) {
        const { value } = e.target.previousElementSibling;
        // Use `value` ...
    }
    

当然,这很脆弱;如果您更改结构,使另一个元素位于 buttoninput 之间,或者 input 在容器元素内,等等,它就会中断——这是一个论据受控方法。您可以在 button:

的数据属性中将 link 存储到 input
<li><input id="id-input" type="text" placeholder="Enter new ID"/>
<button data-input="#id-input" onClick={(e)=>this.saveKonfigElementHandler(e)}>Save</button></li> 

然后用querySelector得到:

saveKonfigElementHandler(e) {
    const { value } = document.querySelector(e.target.getAttribute("data-input"));
    // Use `value` ...
}

但是您必须保持选择器的唯一性等。

你选择,受控或不受控,最终取决于你。

我不确定你的问题。你想要这样的东西吗?

<button data-input="#id-input" onClick={this.saveKonfigElementHandler(value)}>Save</button></li>

saveKonfigElementHandler = (value) => (event) => {}

A modern way to do it,带有函数组件、钩子和受控表单元素,是:

import { useState } from 'react'

function MyComponent({ initialId, onSave }) {
  const [newId, setNewId] = useState(initialId)

  return (
    <li>
      <input 
        type="text" 
        placeholder="Enter new ID" 
        onChange={(e) => setNewId(e.target.value)} 
      />
      <button onClick={() => onSave(newId)}>Save</button>
    </li>
  )
}

我还注意到 it is considered better accessibility practice 使用 label 元素来描述字段的用途,而不是占位符。占位符更适合示例输入。