为什么当我从自定义 React Hooks 返回输入组件时,焦点会从 HTML 输入元素中松动?



我创建了一个useInput自定义钩子,它返回Componentstatestate setter

import React, { useState } from "react";
const useInput = (initialValue = "", label) => {
const [inputState, setInputState] = useState(initialValue);
const id = `use-input-${label.replace(" ", "").toLowerCase()}`;
const handleInputChange = event => {
console.log("calling");
setInputState(event.target.value);
};
const Input = () => {
return (
<label htmlFor={id}>
{label}
<input
className='form-control'
value={inputState}
onChange={handleInputChange}
/>
</label>
);
};
return [Input, inputState, setInputState];
};
export default useInput;

当我按如下所示使用此组件时,焦点会从HTML input组件中松开。

从"反应"导入反应;

import useInput from "./useInput";
function App() {
const [TodoTextInput, todoText, setTodoText] = useInput("", "Create Todo");
return (
<>
<TodoTextInput />
{todoText}
</>
);
}
export default App;

谢谢

您将在每个渲染上重新创建Input组件。而是在useInput中渲染输入,并在App中使用渲染的实例:

const { useState } = React;
const useInput = (initialValue = "", label) => {
const [inputState, setInputState] = useState(initialValue);
const id = `use-input-${label.replace(" ", "").toLowerCase()}`;
const handleInputChange = event => {
console.log("calling");
setInputState(event.target.value);
};
// render the input
const input = (
<label htmlFor={id}>
{label}
<input
className="form-control"
value={inputState}
onChange={handleInputChange}
/>
</label>
);

return [input, inputState, setInputState];
};
function App() {
const [todoTextInput, todoText, setTodoText] = useInput("", "Create Todo");
return (
<React.Fragment>
{todoTextInput /* use the rendered instance */}
{todoText}
</React.Fragment>
);
}
ReactDOM.render(
<App />,
root
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

相关内容

  • 没有找到相关文章

最新更新