0

当我在TextArea组件中的textarea上按 Enter 键时,焦点应位于Editor.js组件的textarea中。 这是我的父组件。

  const Content = () => {
      
      return (
        <div>
          <TextArea />
          <Editor />
        </div>
      )
    }

textarea.js(第一个孩子)

 const TextArea = () => {
        function handleChange(e){
         //if e.target.value will be that of enter , bring focus to textarea of Editor.js  
        }
        return (
        <div>
            <textarea
            onChange={handleChange} 
            />
        </div>
        )

编辑器.js

 const Editor = () => {
            return (
            <div>
                <textarea/>
            </div>
            )
4

1 回答 1

2

这是你如何处理它:


const TextArea = React.forwardRef((props, ref) => {
  const {editorRef} = props;
  function handleChange(e) {
    //if e.target.value will be that of enter , bring focus to textarea of Editor.js
    if(editorRef.current){
      editorRef.current.focus();
    }
  }
  return (
    <div>
      <textarea ref={ref} onChange={handleChange} />
    </div>
  );
});

const Editor = React.forwardRef((props, ref) => {
  return (
    <div>
      <textarea ref={ref} />
    </div>
  );
});

const Content = () => {
  const textAreaRef = useRef();
  const EditorRef = useRef();

  return (
    <div>
      <TextArea ref={textAreaRef} editorRef={EditorRef}/>
      <Editor ref={EditorRef} textAreaRef={textAreaRef} />
    </div>
  );
};

这是一个可以测试的工作沙盒:https ://codesandbox.io/s/stoic-varahamihira-rp84h?file=/src/App.js

于 2020-12-26T16:31:29.267 回答