首页 > 解决方案 > React:从单独的文件中返回函数结果

问题描述

我是 React 新手,目前正在通过构建一个项目来学习。

我有一个名为 Function.js 的文件,其中包含一个我导入到我的组件文件 (Component.js) 中的函数。

我正在尝试在 Function.js 中返回函数的值并将其插入到 div 中,但我不太确定如何解决这个问题......

函数.js

let testVariable;
export const getValue = (getValue) => {
    switch (getIC) {
        case "testing":
            testVariable = "VALUE"
    }
    return testVariable
}

组件.js

import React, { useState } from "react";
import { getValue } from "./testfunc";

function StatusHubContent() {
const [getIC, getValueState] = useState("");

getValue(getIC)

  return (
    <div class="columns is-vcentered">
        <div class="select">
          <select
            id="ic"
            onChange={(e) => {
              getValueState(e.target.value);
            }}
          >
            <option selected disabled>
              Person
            </option>
            <option value="Person A">Person A</option>
            <option value="Person B">Person B</option>
          </select>
        </div>

        <div>{getValue}</div>
    </div>
  );
}

我坚持如何返回值<div></div>

谢谢大家!

标签: reactjs

解决方案


你在做什么,也许我能帮上忙。无论如何,这就是我想出的

函数.js

let testVariable;
export const getValue = (value) => {
    switch (value) {
        case "testing":
            testVariable = "VALUE"
    }
    return testVariable
}

组件.js


import React, { useState } from "react";
import { getValue } from "./testfunc";

function StatusHubContent() {
const [state, setState] = React.useState(null)

return (
    <div class="columns is-vcentered">
        <div class="select">
          <select
            id="ic"
            onChange={(e) => setState(getValue(e.target.value))}
          >
            <option selected disabled>
              Incident Commander
            </option>
            <option value="ayushl">Ayush Lal</option>
            <option value="barriep">Barrie Pocock</option>
            <option value="joeld">Joel Douglas</option>
            <option value="nevashr">Nevash Reddy</option>
            <option value="schalkb">Schalk Burger</option>
          </select>
        </div>

        <div>{state}</div>
    </div>
  );
}


推荐阅读