【问题标题】:How to render String of functional component in React? [duplicate]如何在 React 中渲染功能组件的字符串? [复制]
【发布时间】:2019-03-15 13:08:20
【问题描述】:

我有从数据库渲染组件的用例。在数据库中,它们以字符串格式存储,如下所示:

let Sample = `({firstName})=><h1>My name is {firstName}</h1>`;

当我尝试在反应中渲染它时,它显示为字符串。如何渲染字符串类型的功能组件。

class App extends Component {

  this.state = {
  "sathish" : "firstName",
  }

  render (){
      // how do it use string of functional component like below
      return <Sample firstName={this.state.firstName} />
   }
}

【问题讨论】:

  • 我不喜欢这种方法。你为什么要这样做
  • 你知道Sample是一个字符串吗?
  • 删除反引号
  • 是的,我知道,但它们存储为字符串..我希望这个字符串转换功能组件...我该怎么做?

标签: javascript database reactjs case render


【解决方案1】:

您可以为此使用 eval: 让样本 = eval(({firstName})=&gt;&lt;h1&gt;My name is {firstName}&lt;/h1&gt;);

或更复杂的解决方案是https://babeljs.io/docs/en/babel-parser#example

【讨论】:

  • 这不是他要找的东西
  • OP 说他们将这些组件字符串存储在数据库中。
猜你喜欢
  • 2018-08-30
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 2018-02-17
  • 2019-01-06
相关资源
最近更新 更多