【问题标题】:Convert String in React Components在 React 组件中转换字符串
【发布时间】:2017-11-19 07:38:56
【问题描述】:

我有一个字符串,它实际上是一个带有 props 的嵌套反应组件名称。想要在另一个反应组件中呈现该字符串。 例如

var String = "<parentComponent title='Parent'><childComponent age='23'></childComponent></parentComponent>"

反应代码:-

class MainComponnet extends Component{
 render(){
  let stringComponents = "<parentComponent title='Parent'><childComponent age='23'></childComponent></parentComponent>";
  return(
     {stringComponents}
  )
 }
}

父组件 JSX:-

class ParentComponent extends Component{
 render(){
  return(
     <div> {this.props.title}</div>
  )
 }
}

子组件 JSX:-

class ChildComponent extends Component{
 render(){
  return(
     <div> {this.props.age}</div>
  )
 }
}

请帮忙..

【问题讨论】:

  • 一个问题,为什么它在一个字符串中?
  • 实际上服务将返回组件字符串,因此我必须渲染该组件。
  • 我认为这样做有点不可能。可能你需要一个 react-jsx-parser 在这里将你的字符串转换为普通的组件类型的东西,然后渲染它
  • 谢谢维韦克。我正在网上寻找这样的解析器,运气不好。有什么方法可以帮助我
  • 不确定,但你可以试试这个github.com/TroyAlford/react-jsx-parser

标签: javascript html reactjs react-jsx


【解决方案1】:

该字符串有 JSX 内容,可以直接渲染 JSX 内容,并且组件名称必须以大写字符开头。

看到这个答案:React - Adding component after AJAX to view

class MainComponnet extends Component{
 render(){
  let stringComponents = <ParentComponent title='Parent'><ChildComponent age='23'></ChildComponent></ParentComponent>;
  return(
     </div>{stringComponents}</div>
  )
 }
}

如果你不能直接使用 JSX 元素,你可以使用 babel 将你的字符串转换为 JSX。然而,这不是一个好主意。你应该修改你的逻辑。

你可以这样做

import babel from 'babel-core';
var Component = eval(babel.transform('<ParentComponent title='Parent'><ChildComponent age='23'></ChildComponent></ParentComponent>).code);

【讨论】:

  • 感谢@Shubham 的回复,但如果你注意到我的字符串被双引号包围,而你的不是。它的数据类型是字符串,因此在渲染它不处理反应组件时。
  • 正是我的意思,你不需要将你的字符串用双引号括起来,直接将 JSX 内容分配给变量
  • 我没有任何其他选择,这就是从后端获取 json 的内容。如果我可以删除 UI 上的引号或任何其他从 String 加载组件的方式会有所帮助。
  • 在答案中添加了该部分
【解决方案2】:

非常感谢每一位帮助我的人。 库 'react-jsx-parser' 解决了我的问题。

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 2021-08-20
    • 2017-12-07
    • 2021-05-13
    • 1970-01-01
    • 2017-06-10
    • 2021-05-09
    • 2023-03-19
    相关资源
    最近更新 更多