React拒绝在键入时继续关注输入字段。
我已尝试修复它,但未成功。我不了解这种行为。
这是组件:
import React, { useState } from 'react'
import styled from 'styled-components'
const Auth = () => {
const Form = styled.form``
const InputGroup = styled.div``
const Input = styled.input``
const Button = styled.button``
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<Form>
<InputGroup>
<Input
value={email}
onChange={event => {
setEmail(event.target.value)
}}
type="email"
/>
</InputGroup>
<InputGroup>
<Input
value={password}
onChange={event => {
setPassword(event.target.value)
}}
type="password"
/>
</InputGroup>
<Button />
</Form>
)
}
export default Auth
答案 0 :(得分:5)
问题在于您正在函数内部定义Input组件,每次都会创建一个新元素,因此新输入失去了焦点。 要解决问题,请在功能之外定义组件。
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import styled from "styled-components";
const Form = styled.form``;
const InputGroup = styled.div``;
const Input = styled.input``;
const Button = styled.button``;
const Auth = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<Form>
<InputGroup>
<Input
value={email}
onChange={event => {
setEmail(event.target.value);
}}
type="email"
/>
</InputGroup>
<InputGroup>
<Input
value={password}
onChange={event => {
setPassword(event.target.value);
}}
type="password"
/>
</InputGroup>
<Button>press me</Button>
</Form>
);
};
function App() {
return (
<div className="App">
<Auth />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);