反应将字符串转换为反应组件
react convert strings to react components
所以这可能有点奇怪,我有一个字符串数组和一堆 React 组件。
例如:
const str = ['server','volume','route']
const Server = () => 'This is a server'
const Volume = () => 'This is a server'
等等,你懂的。
我正在尝试将 str 映射到匹配的反应组件和 return 组件。
我知道我可以使用一个循环和一个开关来检查每个项目和 return 相应的组件,但是有没有像这样的创意:
{str.map(Y => <Y />)}
不是很常见的用例,但绝对有可能。
首先将所有项目变成组件
const data = const str = ['server','volume','route']
const components = data.map(x => props => <div {...props}>{x}</div>)
现在渲染每一个
return components.map((Component, i) => <Component key={i} customProp='foo'/>)
您需要使用一个对象作为组件映射,如下所示:
const componentsMap = {
"server": Server,
"route": Route,
"volume": Volume
}
{str.map(key => {
const TheComponent = componentsMap[key];
return <TheComponent />
})}
所以这可能有点奇怪,我有一个字符串数组和一堆 React 组件。 例如:
const str = ['server','volume','route']
const Server = () => 'This is a server'
const Volume = () => 'This is a server'
等等,你懂的。
我正在尝试将 str 映射到匹配的反应组件和 return 组件。
我知道我可以使用一个循环和一个开关来检查每个项目和 return 相应的组件,但是有没有像这样的创意:
{str.map(Y => <Y />)}
不是很常见的用例,但绝对有可能。 首先将所有项目变成组件
const data = const str = ['server','volume','route']
const components = data.map(x => props => <div {...props}>{x}</div>)
现在渲染每一个
return components.map((Component, i) => <Component key={i} customProp='foo'/>)
您需要使用一个对象作为组件映射,如下所示:
const componentsMap = {
"server": Server,
"route": Route,
"volume": Volume
}
{str.map(key => {
const TheComponent = componentsMap[key];
return <TheComponent />
})}