gpt4 book ai didi

javascript - 如何使用 useReducer 实现 react 控制输入?

转载 作者:行者123 更新时间:2023-12-02 00:00:41 25 4
gpt4 key购买 nike

我的目标是使用 useReducer Hook 实现 React 控制的输入。

在 reducer 内部,我需要 event.target.valueevent.target.selectionStart 来获取当前值和插入符号位置。所以我考虑过将 event 作为 ON_CHANGE 操作的 payload 发送。

这就是我正在尝试的:

https://codesandbox.io/s/optimistic-edison-xypvn

function reducer(state = "", action) {
console.log("From reducer... action.type: " + action.type);
switch (action.type) {
case "ON_CHANGE": {
const event = action.payload;
const caretPosition = event.target.selectionStart;
const newValue = event.target.value;
console.log("From reducer... event.target.value: " + event.target.value);
console.log(
"From reducer... event.target.selectionStart: " + caretPosition
);
return newValue;
}
default: {
return state;
}
}
}

export default function App() {
console.log("Rendering App...");

const [state, dispatch] = useReducer(reducer, "");

return (
<div className="App">
<input
value={state}
onChange={event => dispatch({ type: "ON_CHANGE", payload: event })}
/>
</div>
);
}

它适用于输入的第一个字母,但在第二个字母时会中断。

这是错误:

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See react-event-pooling for more information.

我该怎么办?我需要在哪里调用 event.persist()。我应该在 reducer 上执行此操作,还是需要在将其作为参数发送之前在 onChange() 处理程序中执行此操作。

还是只发送这些属性而不是发送完整的 event 对象更好?

喜欢:

onChange={ event => 
dispatch({
type: "ON_CHANGE",
payload: {
value: event.target.value,
caretPosition: event.target.selectionStart
}
})
}

最佳答案

只需传递 event.target.value 即可,因为如错误所述,synthetic events不要坚持。

function reducer(state = "", action) {
switch (action.type) {
case "ON_CHANGE": {
const newValue = action.payload;
return newValue;
}
default: {
return state;
}
}
}

export default function App() {
const [state, dispatch] = useReducer(reducer, "");

return (
<div className="App">
<input
value={state}
onChange={event =>
dispatch({ type: "ON_CHANGE", payload: event.target.value })
}
/>
</div>
);
}

Edit naughty-wind-egone

关于javascript - 如何使用 useReducer 实现 react 控制输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61835326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com