在渲染的组件中包含组件挂载点内容

2024-04-26

我有一个应用程序(内置于 Rails 中),它在后端呈现一些标记,然后我想使用 ReactJS 在前端通过附加功能来“增强”这些标记。

渲染内容看起来像这样:

<%= react_component :TestComponent do %>
    <div class="foo">
        Here's some content.
    </div>
<% end %>

此调用创建一个包装 div,其中包含一些内容data-然后,react_ujs 捕获以实例化 React 组件的属性。我没能做的是找到一种方法(不使用 jquery 做一些有点疯狂的技巧)来获取这个 mount 元素的内容(因此,带有类“foo”的内部 div 及其内容)在我的React 组件,这样我就可以将它包含在我的 JSX 中。

React.createClass({
    render: function() {
        return (
            <div className="my-component">
                { mount point contents here! }
            </div>
        );
    }
});

该行为在 AngularJS 术语中被描述为“嵌入”。

有什么想法可以用 ReactJS 来实现这种行为吗?我收到了一些关于this.props.children,但这似乎并没有产生我需要的结果,并且将会undefined即使这样, mount 元素也有内容。


React 不支持此功能。 React 在真正的 HTML 中不起作用;它在函数调用中起作用。尽管 JSX 看起来像 HTML,但它在由 React 运行之前会被编译为函数调用。这意味着 React 不知道如何处理真正的 HTML,就像您在示例中传递的那样。

JSX:

<div className="foo">
  Here's some content
</div>

尽管这看起来与您尝试注入的内容相似,但客户端最终会看到以下内容:

React:

React.DOM.div({className: "foo"},
  "Here's some content"
)

Your react_component助手应该接受 JSX(而不是 HTML)并通过 JSX 转换器运行它,然后再将其渲染到页面。然后您可以将结果传递给组件并将其引用为this.props.children.

这就是你的react_component应该为您的示例输出:

React.renderComponent(
  TestComponent(null,
    React.DOM.div({className: "foo"},
      "Here's some content"
    )
  ),
  referenceToDomNode // Not obvious where you pass this with your helper
);

和你的TestComponent可能看起来像这样:

var TestComponent = React.createClass({
  render: function() {
    return (
      <div className="my-component">
        {this.props.children}
      </div>
    );
  }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在渲染的组件中包含组件挂载点内容 的相关文章

随机推荐