gpt4 book ai didi

reactjs - React 在打字时取消输入字段的焦点

转载 作者:行者123 更新时间:2023-12-03 13:42:38 25 4
gpt4 key购买 nike

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

codesandbox working example of the problem

最佳答案

问题是您在函数中定义输入组件,每次都会创建新元素,因此您的新输入失去了焦点。要解决问题,请在函数之外定义您的组件。

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);

关于reactjs - React 在打字时取消输入字段的焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56795727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com