输入时反应输入失去焦点

时间:2020-07-06 18:18:34

标签: javascript reactjs react-hooks

我不明白为什么当在另一个组件中定义该组件时,输入一个字符后输入会失去焦点。我读了其他答案以使用ref。但这不起作用。

不起作用:

import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";


function MyApp() {
  const [text1, setText1] = useState("");
  const [text2, setText2] = useState("");
  const ref1 = useRef(null)
  const ref2 = useRef(null)

  const TextInput = ({ref, text, onChange }) => {
    return <input ref={ref} defaultValue={text} onChange={onChange} />;
  };
  

  const onChange1 = e => {
    setText1(e.currentTarget.value);
  };

  const onChange2 = e => {
    setText2(e.currentTarget.value);
  };
  return (
    <form className="App">
      <TextInput ref={ref1} text={text1} onChange={onChange1} />
      <TextInput ref={ref2} text={text2} onChange={onChange2} />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyApp />, rootElement);

当我定义外部组件时,一切正常。

可行吗?

import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";


const TextInput = ({ref, text, onChange }) => {
  return <input ref={ref} defaultValue={text} onChange={onChange} />;
};


function MyApp() {
  const [text1, setText1] = useState("");
  const [text2, setText2] = useState("");
  const ref1 = useRef(null)
  const ref2 = useRef(null)



  const onChange1 = e => {
    setText1(e.currentTarget.value);
  };

  const onChange2 = e => {
    setText2(e.currentTarget.value);
  };
  return (
    <form className="App">
      <TextInput ref={ref1} text={text1} onChange={onChange1} />
      <TextInput ref={ref2} text={text2} onChange={onChange2} />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyApp />, rootElement);

JS Fiddle

1 个答案:

答案 0 :(得分:1)

每当输入值更改并且TextInput组件呈现时,您都在重新创建MyApp。如果要在TextInput组件中包含MyApp组件,则可以使用useCallback钩子来防止渲染组件时重新创建TextInput

JSFiddle

import React, { useState, useRef, useCallback } from "react";
import ReactDOM from "react-dom";

function MyApp() {
      const [text1, setText1] = useState("");
      const [text2, setText2] = useState("");
      const ref1 = useRef(null);
      const ref2 = useRef(null);

      const TextInput = useCallback(({ ref, text, onChange }) => {
        return <input ref={ref} defaultValue={text} onChange={onChange} />;
      }, []);

      const onChange1 = e => {
        setText1(e.currentTarget.value);
      };

      const onChange2 = e => {
        setText2(e.currentTarget.value);
      };
      return (
        <form className="App">
          <TextInput ref={ref1} text={text1} onChange={onChange1} />
          <TextInput ref={ref2} text={text2} onChange={onChange2} />
        </form>
      );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyApp />, rootElement);