我试图找到一种方法来动态调用给定字符串的函数或引用给定字符串的变量。例如:
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>
</>
);
}
如果您不希望一直移动useReducer
到某个位置,那么最好保留一个对象,useState
而不是useState
对每个单独的字段进行单独的调用:
import React, {useState} from 'react'
const array = [
{
text: 'count1',
otherdata: {}
},
{
text: 'count2',
otherdata: {}
}
]
const myFunction = () => {
// This could even be initialised based on the items in `array`
const [count, setCount] = useState({
count1: 0,
count2: 0,
});
return(
<div>
{array.map((item, index) => {
// I want to use item.text to reference the correct count variable
const countValue = count[item.text];
const updateCount = () => {
setCount((prevCount) => {
return {
...prevCount,
[item.text]: prevCount[item.text] + 1,
};
});
};
return (
<button key={index}
onClick={updateCount}
>{item.text}: { countValue }</button>
);
})}
</div>
)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句