如何从React组件中的另一个文件调用函数

时间:2019-10-13 00:01:27

标签: javascript reactjs

我想从React组件调用一个函数。此函数将在调用它的组件中调用另一个函数。

我的组件

import React, { useState } from "react";

// import turnOnGreenLight from "./green.js"; // <-- I want to import this

export const initialLightValues = ["unactive", "unactive"];
export let setLightsVar = initialLightValues;

function App() {

  const [lights, setLights] = useState(initialLightValues);

  function turnOnRedLight() {
    setLightsVar[0] = "active";
    updateLightsState();
    turnOnGreenLight();
  }

  // I want to move this function "turnOnGreenLight" in the file green.js
  function turnOnGreenLight() {
    setLightsVar[1] = "active";
    updateLightsState();
  }

  function updateLightsState() {
    setLightsVar = setLightsVar.slice();
    setLights(setLightsVar);
  }

  return (
    <div className="App">
      <button onClick={() => turnOnRedLight()}>Turn on the lights</button>
      <br />
      <div className={"red-light " + lights[0]}>Red</div>
      <div className={"green-light " + lights[1]}>Green</div>
    </div>
  )
}

export default App

green.js文件中的函数如下所示:

import { setLightsVar, updateLightsState } from "./App";

function turnOnGreenLight() {
  setLightsVar[1] = "active";
  updateLightsState();
}

export default turnOnGreenLight;

我不知道如果我想要做的是可能的。

1 个答案:

答案 0 :(得分:1)

有可能,但是您将得到循环模块警告,并且如果您运行开玩笑的测试,它将抛出异常,因此,如果您希望这样做更好地将函数updateLightsState用作回调参数-则没问题

function turnOnGreenLight(callback) {
  setLightsVar[1] = "active";
  callback();
}

turnOnGreenLight(updateLightsState)