将函数从子组件传递到父组件| Next.js

iszxjhcz  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(238)

因此,我在子组件中有一个函数,它生成图像,在父组件中也有一个按钮,单击该按钮时需要启动子组件中的函数
孩子

const ImgCreate = (props: any) => {
  const [image, setImage] = useState([]);

  const ImgGeneration = async () => {
    const response = await openai.createImage({
      prompt: `${props.inputValue}`,
      n: 2,
      size: "512x512",
    });
    const url = response.data.data;
    
    {  /*@ts-ignore*/}
    setImage(url);


  };



return (
    <div className="mt-10">
      <div className="flex overflow-x-scroll gap-5">
        {image.map((img, index) => (
          <img
            src={img.url}
            key={index}
            className="mt-7 rounded-lg shadow-md"
            alt="Image"
          />
        ))}
      </div>
</div>

父级

const Search = (props: any) => {
  const [search, setSearch] = useState("");

  const handleSearch = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSearch(""); // clear search input
  };
  return (
    <>
      <form
        onSubmit={handleSearch}
        className="flex items-center justify-center gap-6"
      >
        <input
          type="text"
          className="border-2 border-gray-300 p-2 rounded-lg outline-none transition-all duration-100 focus:border-blue-500"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Image Description"
        />
        <button
          type="submit"
          className="btn bg-blue-500 text-white rounded-lg font-bold py-2 px-4"
        >
          Create
        </button>
      </form>
      <ImgCreate inputValue={search} />
    </>
  );
};

所以submit类型的按钮,还需要有一个onClick事件,触发子组件中的**ImgGeneration()**函数
我的一切力量,没有一件是有效的

dxpyg8gm

dxpyg8gm1#

useRef可以与fowardRef一起使用

const Search = (props: any) => {
    const childRef = useRef();
  
     const handleSearch = (e: FormEvent<HTMLFormElement>) => {
       e.preventDefault();
       setSearch(""); // clear search input
       childRef.current.ImgGeneration() // calls child method
    };
     <ImgCreate ref={childRef} inputValue={search} />

}

子元件

const ImgCreate =  forwardRef((props: any) => {
  const [image, setImage] = useState([]);
   
   useImperativeHandle(ref, () => ({

     async ImgGeneration()  {
      const response = await openai.createImage({
        prompt: `${props.inputValue}`,
        n: 2,
        size: "512x512",
       });
       const url = response.data.data;
    
       {  /*@ts-ignore*/}
       setImage(URL); 
     };

    }));

  ...
)}

相关问题