问题描述
我想向非 React 站点添加一个 React 组件、一个评论功能.
I want to add a react component, a comments feature, to a non-react site.
该网站有一个无限滚动的新闻页面.在每个新闻故事下,我想包括反应评论组件.我计划在此处的 FB 教程之后对其进行建模:http://facebook.github.io/react/docs/tutorial.html
The site has a news page with infinite scrolling. Under each news story I want to include the react comments component. I plan to model it after the FB tutorial here: http://facebook.github.io/react/docs/tutorial.html
我的问题是,如何将每个 React 组件动态挂载到 DOM 故事元素?基本上,我希望有许多相同的 React 评论组件实例,但每个实例都与一个独特的故事 (div) 相关联.
My question is, how do I dynamically mount each React component to a DOM story element? Basically, I want to have many instances of the same react comments component, but with each instance tied to a unique story (div).
我觉得我需要在服务器端渲染react组件,在那里我可以动态设置React.renderComponent
.任何指针/示例表示赞赏.
I think I need to render the react component on the server side, where I can dynamically set the React.renderComponent
. Any pointers/examples appreciated.
推荐答案
当添加帖子时,您需要拥有您的数据和目标 dom 节点(我们将这些变量称为 data
和 el)
When the post is added you need to have your data and the target dom node (we'll call these variables data
and el
)
React.render(<MyComponent data={data} />, el);
或者没有 JSX
React.render(React.createElement(MyComponent, {data: data}), el);
清理:
React.unmountComponentAtNode(el);
对于服务器端渲染,您可以:
For server side rendering you can do:
React.renderToString(React.createElement(MyComponent, {data: data}))
只要结果在客户端上以 el
结尾,你就可以用上面提到的 React.render 挂载它.
and as long as the result of that ends up as el
on the client, you can mount it with React.render as mentioned above.
这篇关于同一反应组件的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!