簡體   English   中英

如何從既不是子項也不是父項的組件調用函數?

[英]How do I call a function from component that is not a child nor parent?

組分 A

const 查詢 = ....

獲取數據(查詢);

組分 B

//這里我想使用組件的A參數來調用它

您可能會在這兩個組件周圍有一個父級。 您可以使用父級共享該功能:

function Parent() {
    const [ dataWithQuery, setDataWithQuery ] = useState(null);

    return (
        <>
            <ComponentA setDataWithQuery={ setDataWithQuery  } />
            <ComponentB dataWithQuery={ dataWithQuery } />
        </>
    );
}

在組件 A 中,您將擁有:

function ComponentA({ setDataWithQuery }) {
    const yourQueryHere = '...'

    function getData(query) { ... }

    useEffect(() => {
        setDataWithQuery(() => getData(yourQueryHere));
    }, []);

    ...
}

請注意我在 setDataWithQuery(...) 的行,我創建了一個新函數,該函數使用您的查詢變量調用 getData。 這是您保存要在 ComponentA 之外使用的函數參數的方式。

在組件 B 中,您將擁有:

function ComponentB({ dataWithQuery }) {
    useEffect(() => {
        if(dataWithQuery != null) {
            const data = dataWithQuery();
        }
    }, [ dataWithQuery ]);


    ...
}

但是沒有真正的理由來構建這樣的結構。 為什么不將查詢從 ComponentA 傳遞給父級,使用該查詢從父級獲取數據,然后將該數據傳遞給 ComponentB?

編輯:您還可以查找React Contexts進行共享,而無需上下傳遞父/子。 仍然需要有父母在身邊。

您的意思是,您想將查詢傳遞給 ComponentA,從中獲取數據,然后在 ComponentB 中使用該數據?

如果這不是您想要的並且您想在每個查詢中使用相同的查詢,那么只需將查詢參數保留在它們上面的組件中 post 並在 props 中傳遞它們。

如果前者是你想要的:

父組件:

import "./styles.css";
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";
import { useState } from "react";

    export default function App() {
      const [query, setQuery] = useState("get some data");
      const [data, setData] = useState({});
      return (
        <div className="App">
          <ComponentA query={query} setData={setData} />
          <ComponentB data={data} />
        </div>
      );

組分 A

import React, { useEffect } from "react";

function ComponentA({ query, setData }) {
  useEffect(() => {
    if (query !== "") {
      getData(query);
    }
  }, [query]);

  async function getData(query) {
    //do some stuff
    const result = { id: "1", message: "I am data" };
    setData(result);
  }

  return (
    <div>
      <h1>I am component A</h1>
    </div>
  );
}

export default ComponentA;

組件B

function ComponentB({ data }) {

  function doSomethingWithComponentAData() {
    //do stuff with the data from componentA
  }
  return (
    <div>
      <h1>I am Component B, I got data: {data.id}</h1>
    </div>
  );
}

export default ComponentB;

試試這個:

// Component A

export const getData = () => { // ... }
// Component B

import { getData } from './ComponentA'

const result = getData()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM