我有一个需要,但我似乎无法克服它。
因为我的页面同时使用模板渲染和反应..。我有这个div,它有一个id,让我们说'foo‘。
现在,我想取" foo“的内容,然后用foo的内容呈现我的组件。我的React组件需要有一个特定的外观,但是页面模板有另一个.这说得通吗?
即。
页面呈现方式如下:
<div id="foo">
<ul>
<li>Item One</li>
<li>Item two</li>
</ul>
</div>
然后在我的jsx文件中,我有:
var fooElem = document.getElementById('foo');
var contents = fooElem && fooElem.innerHTML || '';
if(fooElem) {
React.render(
<MyCOMPONENT data={contents} />,
fooElem
);
}
我认为,只要得到div的innerHTML,然后在其中呈现一个包含‘新’组件内容的'innerhtml‘是件容易的事,我抓取的’innerhtml‘。正如您所看到的,我使用“数据”作为支撑,并在组件中使用它再次吐出来,但格式不同。等等。这个"foo“div是由后端返回的,所以除了”尝试获取innerHTML、操作它并将组件呈现到那个空间之外,我不能修改它。“
任何帮助都将不胜感激。
我得到的错误是元素被修改了等等。好像是在循环中。
发布于 2015-07-28 10:58:07
你可以这样做:
'use strict';
var React = require('react');
var myComponent = React.createClass({
getInitialState: function() {
return {
content: ''
};
},
// Learn more about React lifecycle methods: https://facebook.github.io/react/docs/component-specs.html
componentWillMount: function() {
// Get the content of foo
var content = document.getElementById('foo').innerHTML;
// Remove the old templated foo from the page
// This assumes foo is a direct child of document.body
document.body.removeChild(document.getElementById('foo'));
this.setState({
content: content
});
},
render: function() {
<div id={'foo'}>
{this.state.content}
</div>
}
});
// This assumes you want to render your component directly into document.body
React.render(myComponent, document.body);
这将:
foo
的内容读入React组件的状态。foo
元素。foo
)呈现到页面中。https://stackoverflow.com/questions/31669140
复制相似问题