【问题标题】:Only load React compontent on some pages with react-rails仅使用 react-rails 在某些页面上加载 React 组件
【发布时间】:2015-03-25 21:12:07
【问题描述】:

我有一个 ReactJS 组件,我想在 user/show.html 上挂载到 #test-scores。 该组件位于app/assets/javascripts/react-components/test-score.js.jsx

如何确保仅在用户访问user/show 时才加载? 它现在是为每个页面加载的。

app/assets/javascripts/react-components.js:

//= require_tree ./react-components

app/assets/javascripts/react-components/test-score.js.jsx

  1 $( document ).ready( function()  {
  2
  3   var TestResultBox = React.createClass({
  4     loadTestScoreFromServer: function() {
  5       $.ajax({
  [snipp...]
 74   React.render(
 75     <TestResultBox />,
 76     document.getElementById('test-scores')
 77   );

这会导致一个 JS 错误,破坏其他东西:

react.js?body=1:20238 Uncaught Error: Invariant Violation:
_registerComponent(...): Target container is not a DOM element.

对我应该如何构建事物有任何建议吗? :-)

干杯, 马丁

【问题讨论】:

    标签: ruby-on-rails reactjs react-rails


    【解决方案1】:

    这是一个“好的错误”,因为它让您在尝试访问之前知道该节点在 DOM 中不存在。您可以先轻松检查节点是否存在,例如:

    var scores = document.getElementById('test-scores')
    if ( scores ) {
        React.render(<TestResultBox />, scores);
    }
    

    jQuery 有一个忽略错误的坏习惯,但是如果你想使用 jQuery,这样的事情会起作用:

    $('#test-scores').each(function() {
        React.render(<TestResultBox />, this);
    })
    

    【讨论】:

    • 谢谢,就是这样! :-)
    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多