首页 > 解决方案 > 使用函数 Javascript/React 中的字符串动态调用函数/变量

问题描述

我试图找到一种方法来动态调用给定字符串的函数或引用给定字符串的变量。例如:

import React, {useState} from 'react'

const array = [
  {
    text: 'count1',
    setFunctionName: 'setCount1',
    otherdata: {}
  },
  {
    text: 'count2',
    setFunctionName: 'setCount2',
    otherdata: {}
  }
]

const myFunction = () => {
  const  [count1, setCount1] = useState(0)
  const  [count2, setCount2] = useState(0)

  return(
     <div>
       {array.map((item) => {
          // I want to use item.text to reference the correct count variable
          // I want to use item.setFunctionName to change the correct count 
        })}
     </div>
  )
}

具体用例是我想创建一个可重用的侧边栏菜单,其中链接的数据存储在单独文件中的对象数组中。一些菜单项将具有可折叠的子菜单,我需要使用状态管理子菜单的打开和关闭。例子:

import { Button, Collapse } from 'react-bootstrap'

function Example() {
      const [open, setOpen] = useState(false);
    
      return (
        <>
          <Button
            onClick={() => setOpen(!open)} //**I want to dynamically set this when mapping over the array**
          >
            click
          </Button>
          <Collapse in={open}> //**I want to dynamically set this when mapping over the array**
            <div id="example-collapse-text">
              This is example collapsed text
            </div>
          </Collapse>
        </>
      );
    }

标签: javascriptreactjsreact-hooks

解决方案


实现这一点的最佳方法可能是使用减速器。

https://reactjs.org/docs/hooks-reference.html#usereducer

可能是这样的?

const initialState = {count1: 0, count2: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'setCount1':
      return {
        ...state,
        count1: action.value
      };
    case 'setCount2':
      return {
        ...state,
        count2: action.value
      };
    default:
      throw new Error();
  }
}

const array = [
  {
    text: 'count1',
    setFunctionName: 'setCount1',
    otherdata: {}
  },
  {
    text: 'count2',
    setFunctionName: 'setCount2',
    otherdata: {}
  }
]

const myFunction = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return(
     <div>
       {array.map((item) => {
          return <a onClick={ () => dispatch({ type: item.setFunctionName, value:3 }) }>{state[item.text]} <a/>
        })}
     </div>
  )
}

推荐阅读