响应HTML选择元素onChange函数,尝试访问"event.target.value" [英] React HTML select element onChange function, trying to access 'event.target.value'

查看:46
本文介绍了响应HTML选择元素onChange函数,尝试访问"event.target.value"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React中使用受控的HTML < select> 标记时.

When using a controlled HTML <select> tag in React.

关于以下代码段:

为什么有效:

选项1

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

这不是吗?(仅适用于第一个更改)

And this doesn't? (it works only on the first change)

选项#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 重复使用 synthetic事件,这意味着函数执行完成后,它会使event 属性无效.://reactjs.org/docs/events.html#event-pooling"rel =" nofollow noreferrer> 事件池 .

Here event (onChange) is a synthetic event. React re-uses synthetic events, which means when the function execution completes, it nullifies the event properties in the event pool.

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

Since setState is async and event gets nullified after onChange is invoked, directly accessing event properties (i.e event.target.value) within the async callback won't work.

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

One way is to store the value from a synthetic event into a variable like:

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

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

文档

如果要以异步方式访问事件属性,则应在事件上调用 event.persist(),这将从池中删除综合事件并允许引用该事件由用户代码保留.

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
    });
  });
}

演示

这篇关于响应HTML选择元素onChange函数,尝试访问"event.target.value"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆