使用受控 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
属性无效。 .
由于 setState
是 async
并且 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
});
});
}
关于javascript - React HTML选择元素onChange函数,尝试访问 'event.target.value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807849/