当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why React.Component only rendering once even when I have multiple target elements

问题描述:

I'm trying to create a widget with React that would render many times one a page (say a special button widget).

I'm defining my classes in ES6 style like this:

export default class myWidget extends React.Component{

..."constructor and other methods"....

render(){

return <div className="myButtonStyles">Click me</div>;

}

}

My html simply have several identical elements and jQuery selector:

$(document).ready(function(){

$.each($('.myWidget'), function(index, element){

ReactDOM.render(

<App/>,

element

);

})

});

<div>First one <span class="myWidget"/></div>

<div>Second one <span class="myWidget"/></div>

<div>A third <span class="myWidget"/></div>

When running my code, I get the first one rendered only. No Errors!

I experimented with React.createClass instead and seems to be rendering three times.

What am I missing with React? Any help appreciated.

网友答案:

You should change your span tag to <span class="myWidget"></span>

it works , you can check ---> jsbin

variant with $(document).ready ---> jsbin

class Block extends React.Component {
    render(){
        return (<div>Block</div>);
    }
}

$(document).ready(function(){
    $.each($('.block'), function(index, element){
        ReactDOM.render(
           <Block/>,
           element
        );
    })
});

///html

<body>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</body>
分享给朋友:
您可能感兴趣的文章:
随机阅读: