【问题标题】:React Hooks with Styled Components - Form not workingReact Hooks with Styled Components - 表单不起作用
【发布时间】:2021-06-04 00:18:37
【问题描述】:

所以我将 React Hooks 与样式化组件一起使用,我尝试为表单设置样式,但是当我将其变成样式化组件时,表单不起作用,即您键入一个字母然后表单失去焦点,您必须点击返回输入框,输入一个字母,它再次失去焦点等等......

我也在开发工具中收到此警告,但我真的不明白我需要做什么 -

index.js:27 id 为“sc-eCssSg”的组件 styled.form 已动态创建。 您可能会看到此警告,因为您在另一个组件中调用了 styled。 要解决这个问题,只需在任何渲染方法和函数组件之外创建新的 StyledComponents。 在 LocationForm (https://3deis.csb.app/src/Components/LocationForm.js:31:39) 在 div 在应用程序 (https://3deis.csb.app/src/App.js:53:39)

如何更改以下代码以使其正常工作?

import React, { useState } from "react";
import axios from "axios";
import styled from "styled-components";

const LocationForm = (props) => {
  const [locationName, setName] = useState("");

  const Form = styled.form``;

  const handleSubmit = (evt) => {
    evt.preventDefault();

    axios
      .get(
        `http://www.mapquestapi.com/geocoding/v1/address?key=z2G40AM2VSDfXx7MQtCqAvmXmoYEX8cV&location=${locationName}&maxResults=1`
      )
      .then((res) => {
        const latitude = res.data.results[0].locations[0].displayLatLng.lat;
        const longitude = res.data.results[0].locations[0].displayLatLng.lng;
        const city = res.data.results[0].locations[0].adminArea5;
        // const submitted = !true;

        props.callbackFromParent(
          locationName,
          // submitted,
          latitude,
          longitude,
          city
        );
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <Form onSubmit={handleSubmit}>
      <label>
        Location:
        <input
          type="text"
          value={locationName}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <input type="submit" value="Submit" />
    </Form>
  );
};

export default LocationForm;

【问题讨论】:

  • "要解决这个问题,只需在任何渲染方法和函数组件之外创建新的 StyledComponents"

标签: reactjs forms react-hooks styled-components


【解决方案1】:

它准确地说明了正在发生的事情。您正在 LocationForm 渲染函数中创建 const Form = styled.form。如果您将其移动 4 行,则该功能将停止发出警告。一般来说,您永远不应该在渲染函数中创建样式化组件,因为它会在每次渲染时重新创建表单(因此每次输入字符时),而不是在初始化时只创建一次。

【讨论】:

  • 哦!我明白你的意思,非常感谢您的解释!
  • 很高兴它有帮助。如果它对您的案子有帮助,您介意接受答案吗?
猜你喜欢
  • 2019-04-03
  • 2018-03-06
  • 1970-01-01
  • 2019-09-24
  • 2020-10-19
  • 2021-01-09
  • 2018-04-14
  • 2019-02-18
相关资源
最近更新 更多