javascript - 使用函数 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>
</>
);
}
解决方案
实现这一点的最佳方法可能是使用减速器。
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>
)
}
推荐阅读
- javascript - 如何在 js 或 jQuery 中同时通过 id 和属性定位元素
- c++ - 使用带参数的成员函数了解 std::thread 构造函数调用
- sql-server - 如何使用触发器( SQL Server )更新插入之前存在的行?
- python - 执行矢量化操作时如何在 Pandas 中访问系列的行值
- output - 如何在运行时打印出 Apify requestQueue.getInfo()?
- vb.net - 如何在 Visual Basic 中的图表上绘制垂直线
- c++ - 如何使用继承实现方法链接?
- apache - 选择正确的客户端证书 - https - ssl 相关
- python - 按类打印多个元素时得到一个空列表
- batch-file - 批处理脚本中嵌套标签的奇怪行为