首页 > 解决方案 > 我尝试在我的应用程序中使用样式化组件。但是我写完城市名称后光标会移开

问题描述

在搜索区域中,每次我输入任何字母时,光标都会移出,我需要再次单击文本区域才能输入下一个字母。在使用 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;

标签: cssreactjsstyled-components

解决方案


每当您对输入进行更改时,看起来值正在更改(或刷新),因为它与状态绑定并且状态正在更新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}
/>

让我知道它是否有效。


推荐阅读