我已经尝试在我的应用程序中使用样式组件.但在我写下城市名称后,光标会向外移动



在搜索区域中,每次我键入任何字母时,光标都会向外移动,我需要再次单击文本区域来键入下一个字母。当使用CSS时,它工作得很好,但在Styled组件中,我面临着这个问题。我认为我的样式有一些问题,但我无法调试。如何解决此问题。请帮忙。

import React, { FC, useState, FormEvent } from 'react';
import { useDispatch } from 'react-redux';
import styled from 'styled-components';
import { setAlert } from '../store/actions/alertActions';
import { getWeather, setLoading } from '../store/actions/weatherActions';
interface SearchProps {
title: string;
}

const Search: FC<SearchProps> = ({ title }) => {
const dispatch = useDispatch();
const [city, setCity] = useState('');
const changeHandler = (e: FormEvent<HTMLInputElement>) => {
setCity(e.currentTarget.value);
}
const submitHandler = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if(city.trim() === '') {
return dispatch(setAlert('City is required!'));
}
dispatch(setLoading());
dispatch(getWeather(city));
setCity('');
}

const Header = styled.h1`
font-size: 40px;
font-family:  'sans-serif';
padding-top: 30px;
`;
const Input = styled.input`
font-size: 18px;
padding: 10px;
margin: 10px;
background: #b4e6df;
border: none;
border-radius: 3px;
::placeholder {
color: black;

}
`;
const Button = styled.button`
background-color: #10e2f1;
font-size: 20px;
color: white;
margin: 1em;
border: 3px;
padding: 0.25em 6em;

`;
return(
<>
<Header >{title}
<form  onSubmit={submitHandler}>
<Input 
type="text"
placeholder="Enter city name"
value={city}
onChange={changeHandler}
/>
<br/>
<Button >Search</Button>
</form>
</Header>
</>
);  
}
export default Search;

当您对输入进行更改时,该值似乎正在更改(或刷新(,因为它与状态绑定,并且状态正在更新onChange事件。在value属性中保持独立值而不是状态变量。像这样的东西:

const defaultValue = ''; // or the default value you are getting from props
const [city, setCity] = useState(defaultValue);
---
---
<Input 
type="text"
placeholder="Enter city name"
value={defaultValue}
onChange={changeHandler}
/>

让我知道它是否有效。

最新更新