我不明白为什么当在另一个组件中定义该组件时,输入一个字符后输入会失去焦点。我读了其他答案以使用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);
答案 0 :(得分:1)
每当输入值更改并且TextInput
组件呈现时,您都在重新创建MyApp
。如果要在TextInput
组件中包含MyApp
组件,则可以使用useCallback
钩子来防止渲染组件时重新创建TextInput
。
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);