简体   繁体   English

如何在 React 中调用名称作为道具传递的组件?

[英]How to call a Component which name is passed as props in React?

i'm new at React.我是 React 的新手。 Basically i want to call different components based on the string passed as props.基本上我想根据作为道具传递的字符串调用不同的组件。 I've component named Device that have as prop the name of a particular device and in Device i want to call another components which has as name the props.我有一个名为 Device 的组件,它具有特定设备的名称作为道具,并且在 Device 中我想调用另一个具有道具名称的组件。 Something like this: <DeviceName/>像这样的东西: <DeviceName/>

This is my code: App.js这是我的代码:App.js

<Device name = {devName} />

Device.js设备.js

import DeviceMark from ./devices/DeviceMark
function DeviceName({devName}) {
    const DevName = devName;
    return (
        <Router>
            <Switch>
                <Route path = "/" exact><DevName /></Route>
            </Switch>
        </Router>
    )
}

Imagine that in this case DevName will replace DeviceMark想象一下,在这种情况下 DevName 将替换 DeviceMark

When you really need to convert string component names to actual components while rendering, I can suggest following way当您确实需要在渲染时将字符串组件名称转换为实际组件时,我可以建议以下方式

import DeviceMark from ./devices/DeviceMark

function DeviceName({devName}) {
    const mappingComponents = {
        foo: FooComponent,
        bar: BarComponent,
        deviceMark: DeviceMark
    };
    const ComponentToRender = mappingComponents[devName || 'foo'];
    
    return (
        <Router>
            <Switch>
                <Route path = "/" exact><ComponentToRender></ComponentToRender></Route>
            </Switch>
        </Router>
    )
}

More details in official doc - https://reactjs.org/docs/jsx-in-depth.html官方文档中的更多详细信息 - https://reactjs.org/docs/jsx-in-depth.html

I guess you need to use React.createElement .我猜你需要使用React.createElement It allows to create React element from string (if it's a basic html tag) or from function (if it's a React component).它允许从字符串(如果它是基本的 html 标签)或从 function(如果它是 React 组件)创建 React 元素。

import React from 'react'
import ReactDOM from 'react-dom'

const DeviceName = () => {
  return 'sub component'
}

const Device = ({subDev}) => {
  return (
    <div>
      { React.createElement(subDev) }
    </div>
  )
}

function App() {
  return <Device subDev={DeviceName} />
}

ReactDOM.render(<App />, document.getElementById('root'))

It's a little example.这是一个小例子。 I have a main component Device .我有一个主要组件Device It accepts a sub-component via a prop and I pass sub-component to createElement .它通过道具接受子组件,我将子组件传递给createElement It does not matter if sub-component whether basic html tag or React component.子组件是基本 html 标签还是React组件都没有关系。

It's codesandbox example .这是代码框示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM