猿问

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

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


在减速器内部,我需要并获取当前值和插入记号位置。所以我考虑过将 作为操作发送。event.target.valueevent.target.selectionStarteventpayloadON_CHANGE


这就是我正在尝试的:


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>

  );

}

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


这是错误:


警告:出于性能原因,将重用此综合事件。如果您看到此信息,则表示您正在访问已发布/无效的综合事件的属性。此值设置为空。如果必须保留原始综合事件,请使用 event.persist()。有关详细信息,请参阅。targetreact-event-pooling


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


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


喜欢:


onChange={ event => 

  dispatch({ 

    type: "ON_CHANGE", 

    payload: {

      value: event.target.value,

      caretPosition: event.target.selectionStart

    }

  })

}


绝地无双
浏览 122回答 1
1回答

倚天杖

只需传递,因为就像错误所说的那样,合成事件不会持续存在。event.target.valuefunction reducer(state = "", action) {&nbsp; switch (action.type) {&nbsp; &nbsp; case "ON_CHANGE": {&nbsp; &nbsp; &nbsp; const newValue = action.payload;&nbsp; &nbsp; &nbsp; return newValue;&nbsp; &nbsp; }&nbsp; &nbsp; default: {&nbsp; &nbsp; &nbsp; return state;&nbsp; &nbsp; }&nbsp; }}export default function App() {&nbsp; const [state, dispatch] = useReducer(reducer, "");&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; value={state}&nbsp; &nbsp; &nbsp; &nbsp; onChange={event =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dispatch({ type: "ON_CHANGE", payload: event.target.value })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答