几个月来我第一次使用 react 和钩子。到目前为止,我喜欢它,但我遇到了一个问题,这个问题已经阻止了我几个小时。
我有一个看起来像这样的组件:
import React, { useState } from "react";
import ReactModal from "react-modal";
import { useModal } from "react-modal-hook";
import styled from 'styled-components';
export function SearchImageForm(props) {
const [query, setQuery] = useState("");
const [images, setImages] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
fetch(`myurl&q=${query}`)
.then((response) => {
return response.json();
})
.then((myJson) => {
if (myJson.totalHits > 0) {
setImages(myJson.hits);
showModal(images, handleClick);
}
});
};
const FormWrapper = styled.div`
text-align: left;
`;
const Container = styled.div``;
const LabelEl = styled.label``;
const Input = styled.input``;
const handleClick = (e) => {
const urlField = document.querySelector('#url');
urlField.value = e.target.src;
urlField.select();
document.execCommand("copy");
alert('URL has been copied to your clipboard. You may now paste it into the URL field.')
};
return (
<Container>
<FormWrapper>
<form onSubmit={handleSubmit}>
<LabelEl>
Enter Search Term
<Input type="text" name="query" value={query} onChange={e => setQuery(e.target.value)} />
</LabelEl>
<input type="submit" value="Submit" />
</form>
</FormWrapper>
</Container>
);
}
export default SearchImageForm;
const ImageResult = ({content, handleClick}) => (
<picture>
<img src={content.previewURL} alt="" onClick={handleClick}/>
</picture>
);
const [showModal, hideModal] = useModal(({images, handleClick}) => (<ReactModal isOpen ariaHideApp={false}>
<p>Found {images.length} image(s). Click an image to copy its URL to your clipboard.</p>
{images.map(image => <ImageResult key={image.id} content={image} handleClick={handleClick} />)}
<input type="text" name="url" id="url" key="url" />
<button onClick={hideModal}>Hide modal</button>
</ReactModal>));
当我尝试运行它时,我收到 React 钩子错误(无效的钩子调用(。关于我在这里做错了什么的任何想法?
这是代码沙箱上的代码,尽管我不确定为什么它不会运行。 https://codesandbox.io/s/blue-firefly-0sx6h
谢谢!
useModal
钩子需要在组件内部调用。
从无效的挂机调用警告文档中:
钩子只能在函数组件的主体内部调用。
因此,您需要做的修改如下:
export function SearchImageForm(props) {
const [showModal, hideModal] = useModal(({images, handleClick}) => (
<ReactModal isOpen ariaHideApp={false}>
<p>Found {images.length} image(s). Click an image to copy its URL to your clipboard. </p>
{images.map(image => <ImageResult key={image.id} content={image} handleClick={handleClick} />)}
<input type="text" name="url" id="url" key="url" />
<button onClick={hideModal}>Hide modal</button>
</ReactModal>
));
// ... rest of your component code
return <>{/* your render */}</>
}
我希望这有所帮助!