我创建了一个useInput
自定义钩子,它返回Component
、state
和state 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>