【发布时间】:2015-06-09 01:54:46
【问题描述】:
Here's a js fiddle 显示实际问题。
在组件的渲染函数中,我渲染了一个类.blah的div。在同一组件的componentDidMount 函数中,我希望能够选择类.blah 并像这样附加到它(因为组件已安装)
$('.blah').append("<h2>Appended to Blah</h2>");
但是,附加的内容不显示。我还尝试(也显示在小提琴中)以相同的方式附加,但从父组件到子组件,结果相同,也从子组件到父组件的空间,结果相同。我尝试后者的逻辑是,可以更确定 dom 元素已被渲染。
同时,我能够(在componentDidMount 函数中)添加到getDOMNode 并附加到那个
var domnode = this.getDOMNode();
$(domnode).append("<h2>Yeah!</h2>")
然而,与 CSS 样式有关的原因我希望能够使用我知道的类附加到 div。另外,由于根据docs getDOMNode 已被弃用,并且不可能使用getDOMNode 的替换来做同样的事情
var reactfindDomNode = React.findDOMNode();
$(reactfindDomNode).append("<h2>doesn't work :(</h2>");
我不认为 getDOMNode 或 findDOMNode 是做我想做的事情的正确方法。
问题:是否可以在 React 中附加到特定的 id 或类?我应该使用什么方法来完成我想做的事情(getDOMNode,即使它已被弃用?)
var Hello = React.createClass({
componentDidMount: function(){
$('.blah').append("<h2>Appended to Blah</h2>");
$('.pokey').append("<h2>Can I append into sub component?</h2>");
var domnode = this.getDOMNode();
$(domnode).append("<h2>appended to domnode but it's actually deprecated so what do I use instead?</h2>")
var reactfindDomNode = React.findDOMNode();
$(reactfindDomNode).append("<h2>can't append to reactfindDomNode</h2>");
},
render: function() {
return (
<div class='blah'>Hi, why is the h2 not being appended here?
<SubComponent/>
</div>
)
}
});
var SubComponent = React.createClass({
componentDidMount: function(){
$('.blah').append("<h2>append to div in parent?</h2>");
},
render: function(){
return(
<div class='pokey'> Hi from Pokey, the h2 from Parent component is not appended here either?
</div>
)
}
})
React.render(<Hello name="World" />, document.getElementById('container'));
【问题讨论】:
标签: javascript reactjs