【问题标题】:How to send data created in child to parent using react hook?如何使用反应钩子将孩子创建的数据发送给父母?
【发布时间】:2021-09-10 08:48:08
【问题描述】:

作为问题状态,我要做的是将子值从子传递给父。我想在我的父函数中调用子变量。

父代码

function App() {

  let [value, setVal] = useState(null);
  ...
  const onLayoutChange = (layout) => {
    console.log(value);
    if (value != null) {
      value.resize();
    }
    //   chartInstance.resize();
  };

  return (
    <ResponsiveGridLayout
      layouts={layout}
      onLayoutChange={() => onLayoutChange(layout)}
    >
      <div key="1">
        <Card style={styles} val={setVal} />
      </div>
    </ResponsiveGridLayout>
  );
}

#1 子代码

export default function SimpleCard(props) {
 
  return (
    <Card style={props.style.main}>
      <CardContent>
        <NewvsReturnVisitors value={props.val} />
      </CardContent>
    </Card>
  );
}

#2 子代码

const Newvsresturnvisitors = (props) => {
  ...
  let [val, setVal] = useState(null);

  let chartInstance = null;
  props.value(val);

  function renderChart() {
    const renderInstance = echarts.getInstanceByDom(chart.current);

    if (renderInstance) {
      chartInstance = renderInstance;
      setVal(chartInstance);
    } else {
      chartInstance = echarts.init(chart.current, null, {
        width: 500,
        height: 300
      });

      setVal(chartInstance);
      // chartInstance.resize();
    }
    chartInstance.setOption(option);
  }
  ...
}
export default Newvsresturnvisitors;

我不确定这是否可能,任何建议都非常感谢。

这是我的密码箱的link

【问题讨论】:

标签: reactjs echarts


【解决方案1】:

可以在父组件中创建状态变量,然后将setXXX方法传递给子组件,在子组件中调用setXXX方法将变量传递给父组件。

【讨论】:

  • 我已经编辑了我的问题,所以我尝试了你的方法,但现在我有一个新的警告。 Warning: Cannot update a component (App) while rendering.. 同一个链接,打开控制台,出现警告
  • 你可以尝试移动 console.log(value);脱离 onLayoutChange 函数。
  • 我已经编辑了我的问题,所以我用 if 条件封装了值,并且我的调整大小函数没有执行:(
【解决方案2】:
const changeLayout = (layout) => {
    //   chartInstance.resize();
  };


<ResponsiveGridLayout
      layouts={layout}
      onLayoutChange={changeLayout}
    >

尝试像这样使用道具 li

【讨论】:

    猜你喜欢
    • 2020-12-17
    • 2022-08-03
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多