Include component mount point contents in rendered component

非 Y 不嫁゛ 提交于 2021-01-28 00:21:32

问题


I have an application (built in Rails) that renders some markup in the back-end, which I would then like to "enhance" with additional functionality in the front-end, using ReactJS.

Rendering the content looks something like this:

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

This call creates a wrapper div with some data- attributes that react_ujs then captures to instantiate React components. What I'm failing to do is find a way (short of using jquery to do some mildly crazy tricks) to get the contents of this mount element (so, the inner div with the class 'foo', and its contents) in my React component, so that I can then include it in my JSX.

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

The behavior is what's described in AngularJS terms as a "transclude".

Any ideas how this behavior can be achieved with ReactJS? I've received some pointers towards this.props.children, but this doesn't seem to yield the results I need, and will be undefined even then the mount element has content.


回答1:


This is not supported functionality in React. React doesn't work in real HTML; it works in function calls. Even though JSX looks like HTML, it is compiled to function calls before it is run by React. That means React doesn't know what to do with real HTML like you are passing it in your example.

JSX:

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

Even though that looks similar to the content you are trying to inject, the client ends up seeing this:

React:

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

Your react_component helper should accept JSX (not HTML) and run it through the JSX converter before rendering it to the page. Then you can pass the result to a component and reference it as this.props.children.

This is what your react_component should output for your example:

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

And your TestComponent could look like this:

var TestComponent = React.createClass({
  render: function() {
    return (
      <div className="my-component">
        {this.props.children}
      </div>
    );
  }
});


来源:https://stackoverflow.com/questions/23067765/include-component-mount-point-contents-in-rendered-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!