javascript - React HTML选择元素onChange函数,尝试访问 'event.target.value'

标签 javascript html reactjs react-hooks

使用受控 HTML 时 <select> React 中的标签。

关于下面的代码片段:

为什么这有效:

选项#1

function changeSelect(event) {
  const newValue = event.target.value;
  setNestedState((prevState) => {
    return({
      ...prevState,
      propA: newValue
    });
  });
}

这不是吗? (仅在第一次更改时有效)

选项#2

function changeSelect(event) {
  setNestedState((prevState) => {
    return({
      ...prevState,
      propA: event.target.value
    });
  });
}

SNIPPET(使用选项 #2)

function App() {
  
  const [nestedState,setNestedState] = React.useState({
    propA: 'foo1',
    propB: 'bar'
  });
  
  function changeSelect(event) {
    // const newValue = event.target.value;
    setNestedState((prevState) => {
      return({
        ...prevState,
        propA: event.target.value    // THIS DOES NOT WORK
      });
    });
  }
  
  return(
    <React.Fragment>
      <div>My nested state:</div>
      <div>{JSON.stringify(nestedState)}</div>
      <select 
        value={nestedState.propA} 
        onChange={changeSelect}
      >
        <option value='foo1'>foo1</option>
        <option value='foo2'>foo2</option>
        <option value='foo3'>foo3</option>
      </select>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

最佳答案

这里的事件(onChange)是一个合成事件React 重新使用合成事件,这意味着当函数执行完成时,它会使 event pool 中的 event 属性无效。 .

由于 setStateasync 并且 event 在调用 onChange 后变得无效,因此直接访问事件属性(即异步回调中的 event.target.value) 将不起作用。

一种方法是将合成事件中的值存储到变量中,例如:

function changeSelect(event) {
  const newValue = event.target.value; // reference
  setNestedState((prevState) => {
    return({
      ...prevState,
      propA: newValue // can use event properties
    });
  });
}

使其异步工作的另一种方法是使用 event.persist()

来自docs ,

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

function changeSelect(event) {

  event.persist();   //This will persist the event

  setNestedState((prevState) => {
    return({
      ...prevState,
      propA: event.target.value
    });
  });
}

Demo

关于javascript - React HTML选择元素onChange函数,尝试访问 'event.target.value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807849/

相关文章:

jQuery Mobile 导航栏包装在 4 个(而不是 5 个)元素上

javascript - 在可滚动的 div 中显示图像

javascript - 这是否会将点击事件附加到 anchor 标记?

javascript - 手机和平板电脑的悬停问题

jquery - 无法使用 Jquery 添加的元素执行任何函数

html - 在中间流体布局中垂直显示水平列表

javascript - 我如何将 VaniilaJS 嵌入到 React 中?

javascript - 如何在 React 中显示默认 View ?

javascript - 使用 lodash 并尝试使用多个对象更新和对象。 (编辑项目)

javascript - HTML 脚本和 javascript