简体   繁体   English

调用子组件函数

[英]Calling child component function

So im trying to call a function from child component, but all I do ends up with an error.所以我试图从子组件调用一个函数,但我所做的一切都以错误告终。 I've been searching for more than hour and found many solutions, but most of them are either outdated or I'm doing something wrong.我已经搜索了一个多小时并找到了许多解决方案,但其中大多数要么已经过时,要么我做错了什么。

Here's my parent component and theres simple getData function in child component named Query.这是我的父组件,在名为 Query 的子组件中有简单的 getData 函数。

const ref = useRef();
return(
     <Query ref={ref} />
     <button onClick={() => ref.current.getData()}>dasfas</button>
)

I also tried forwardRef hook, but I couldn't call it anyway.我也尝试过 forwardRef 钩子,但无论如何我都无法调用它。

Move the function to the parent component and pass data to Query component as props.将函数移动到父组件,并将数据作为 props 传递给Query组件。

import React from "react";
import { Grid, Typography } from "@material-ui/core";

const Query = ({ query }) => {

  return (
    <Grid container item sm={12}>
      <Grid item sm={12}>
        <Typography variant="h5">Queries</Typography>
      </Grid>
      <Grid item sm={12}>
        <div id="sqlQuery" />
      </Grid>
      <Grid item sm={12}>
        <div id="treeViewBefore" />
      </Grid>
      <Grid item sm={12}>
        <div id="treeViewAfter" />
      </Grid>
    </Grid>
  );
};

export default Query;

Parent component父组件

import React, { useState } from "react";

const Parent = () => {
  const [sqlQuery, setSqlQuery] = useState("");

  const getData = async () => {
    if (global.answercreated) {
      var response = await fetch(
        `${global.serverURL}?type=before&&property=${global.token}`
      );
      var data = await response.text();
      const jsonbefore = JSON.parse(data.replace(/'/g, '"'));

      response = await fetch(
        `${global.serverURL}?type=after&&property=${global.token}`
      );
      data = await response.text();
      const jsonafter = JSON.parse(data.replace(/'/g, '"'));

      response = await fetch(
        `${global.serverURL}?type=sqlquery&&property=${global.token}`
      );
      data = await response.text();
      const sqlQuery = data;
    }
  };

  return (
    <div>
      <Query query={sqlQuery} />
      <button onClick={() => getData()}>dasfas</button>
    </div>
  );
};

export default Parent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM