用正则表达式替换textarea时如何保存光标位置?

用正则表达式替换textarea时如何保存光标位置?现在键入时,如果文本中有2(2),则将其替换为3,并且光标跳到末尾;如果没有2,则它不会跳。

https://codesandbox.io/s/nifty-haze-rb7kp

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [text, setText] = useState("");
  useEffect(() => {
    setText(text.replace("2", "3"));
  }, [text]);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <textarea value={text} onChange={e => setText(e.target.value)} />
      <br />
      {text}
    </div>
  );
}
评论
zhangferry
zhangferry

您可以从事件中获取selectionStart并使用setSelectionRange设置光标

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [text, setText] = useState("");

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <textarea
        value={text}
        onChange={e => {
          let target = e.target;
          let val = target.value;
          const cursor = e.target.selectionStart;
          val = val.includes("2") ? val.replace("2", "3") : val;
          setText(val);
          setTimeout(() => {
            target.setSelectionRange(cursor, cursor);
          }, 10);
        }}
      />
      <br />
      {text}
    </div>
  );
}
点赞
评论