【发布时间】: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