我试图找到一种方法来动态调用给定字符串的函数或引用给定字符串的变量。例如:
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>
</>
);
}
发布于 2021-01-20 23:07:42
也许是这样的?
import React, { useState } from "react";
const stepOne = () => "This is the step number 1";
const stepTwo = () => "This is the step number 2";
const stepTree = () => "This is the step number 3";
const objectOfFunctions = {
stepOne,
stepTwo,
stepTree
};
const arrayOfStrings = [
"stepOne",
"stepTwo",
"stepTree"
];
export default function App() {
return <div>
{
arrayOfStrings.map( (e, index) => (
<h3 key={index}>
{objectOfFunctions[e]()}
</h3>
))
}
</div>;
}
也可以使用以下组件在运行时将字符串解析为JSX:react jsx-解析器
这样,您就可以拥有这样的字符串:
const str = 'This is a component rendered in runtime {Component}'
它会成功的。
https://stackoverflow.com/questions/65818704
复制相似问题