【问题标题】:load react script inside text/template script在文本/模板脚本中加载反应脚本
【发布时间】:2017-10-20 06:21:57
【问题描述】:

我正在尝试为使用<script type="text/template"></script> 呈现页面元素的项目做出贡献。

我的贡献是将页面的元素变成了 React 组件。但是,当我使用 ReactDOM.render() 命令在特定 div 中呈现反应时,我收到一条错误消息

未捕获的错误:_registerComponent(...):目标容器不是 DOM 元素。

我知道这意味着 react 找不到要渲染的 div,所以我需要在 div 之后加载 react 脚本,我已经尝试过了,但错误又出现了。

我尝试过像这样加载反应脚本

<script type="text/template">   
  <ul class="new-component-template" id="xblocklist" >
  </ul>
  <script type="text/babel" src="path to react file"/>
</script>

但是当我加载页面时,错误消失了,脚本根本没有加载。

我需要的是在调用外部脚本时加载脚本,I.E我可以在&lt;script type="text/template"&gt;&lt;/script&gt;里面写一个函数来实际加载里面的react脚本。

更新

var ListXblocks = React.createClass({

componentWillMount: function(){
 this.setState({Problemstyle: this.props.Problemstyle})
 fetch('http://192.168.33.10:8002/XBlocks/')
 .then(result=>result.json())
 .then(result=> {
   this.setState({items:result})
 })
 },

 render:function(){
 return(

  <div>
    {
      this.state.items.map((item)=>{return(
        <li className="editor-manual" key={item.title}>
          <button type="button" className="button-component" data-category="problem" data-boilerplate="">
            <span className="name">{item.description}</span>
          </button>

        </li>)})

      }
  </div>

  );

  }

  });

  ReactDOM.render(<ListXblocks/>, document.getElementById('xblocklist'));

【问题讨论】:

  • 你能告诉我们ReactDOM.render()如何使用ul标签吗?
  • @TharakaWijebandara 我应该在ul 标签内渲染组件。我更新了我的帖子并添加了反应代码

标签: javascript reactjs templates openedx


【解决方案1】:

带有type="text/template" 的脚本标签没有做任何特别的事情,它只是让浏览器忽略其中的内容。这种方法通常由像handlebarjs 这样的模板系统使用,而React 不支持它。您可以阅读有关此here 的更多信息。所以如果你把你的 React 脚本也放在里面,浏览器也会忽略它。

因为您的 ul 标签不是 html 元素,document.getElementById('xblocklist') 将返回 null。这就是为什么你会得到“目标容器不是 DOM 元素”。错误。因此,您必须手动或使用 JavaScript 从脚本标签中获取 html。

【讨论】:

  • 我猜 HTML 是从脚本标签中提取的,以及指向 react 的脚本,但它只是像 HTML 元素一样打印在那里
猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
相关资源
最近更新 更多