css - 我尝试在我的应用程序中使用样式化组件。但是我写完城市名称后光标会移开
问题描述
在搜索区域中,每次我输入任何字母时,光标都会移出,我需要再次单击文本区域才能输入下一个字母。在使用 CSS 时它工作正常,但在样式化组件中我面临这个问题。我认为我的样式存在一些问题,但我无法调试。我该如何解决这个问题。请帮忙。
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}
/>
让我知道它是否有效。
推荐阅读
- javascript - Nativescript 水平滚动效果很好,但不适用于项目模板
- autodesk-forge - 将 AutoDesk Forge 查看器环境从本地切换到 AutodeskProduction
- ios - 如果用户的信息不正确,如何阻止用户通过登录页面 IOS
- python-3.x - ValueError:尝试在python中对列表进行排序时无法将列转换为布尔值
- authentication - 我的 nuxt-auth 令牌配置正确,但令牌从未存储
- c++ - 如何为 c/c++ 程序生成没有崩溃/段错误的核心转储文件
- android - ArrayList$Itr.next 抛出错误 concurrentModificationException
- python-3.x - Python:在类调用中使用另一个类的函数
- c# - 如何在 C# 中制作移动、平滑的图像背景(Visual Studio 2019)
- css - 如何在更漂亮的 vs 代码中设置逗号