[英]how to use one component render many html fragment in reactjs?
I have a button there, when I click this button, i want render a div
and append it to body
. 我在那里有一个按钮,当我单击此按钮时,我想渲染一个
div
并将其附加到body
。
and when I click this button again, a new div
be rendered. 当我再次单击此按钮时,将呈现一个新的
div
。
I want: How many times I click the button, how many div
be render. 我想要: 单击按钮多少次,渲染多少
div
。
The follow code can only render one div
: ( jsFiddle: http://jsfiddle.net/pw4yq/ ) 以下代码只能呈现一个
div
:(jsFiddle: http : //jsfiddle.net/pw4yq/ )
var $tool = document.getElementById('tool');
var $main = document.getElementById('main');
var partBox = React.createClass({displayName: 'partBox',
render: function(){
return (
React.DOM.div({className:"box"}, "HELLO! ", this.props.ts)
)
}
});
var createBoxBtn = React.createClass({displayName: 'createBoxBtn',
createBox: function(){
var timeStamp = new Date().getTime();
React.renderComponent(partBox( {ts:timeStamp} ), $main);
},
render: function(){
return (
React.DOM.button( {onClick:this.createBox}, "createBox")
)
}
});
React.renderComponent(createBoxBtn(null ), $tool);
Your app should be data driven, meaning the state of your app is kept outside the DOM. 您的应用程序应该是数据驱动的,这意味着您的应用程序状态保持在DOM之外。 In your example, you are essentially keeping a list of Date objects.
在您的示例中,您实际上保留了一个Date对象列表。 Put that into a state that you can modify, and render a box for each Date object you have created:
将其置于可以修改的状态,并为创建的每个Date对象渲染一个框:
Working JSFiddle: http://jsfiddle.net/pw4yq/6/ 工作的JSFiddle: http : //jsfiddle.net/pw4yq/6/
var $main = document.getElementById('main');
var partBox = React.createClass({displayName: 'partBox',
render: function(){
return (
React.DOM.div({className:"box"}, "HELLO! ", this.props.ts)
)
}
});
var createBoxBtn = React.createClass({displayName: 'createBoxBtn',
createBox: function(){
var timeStamp = new Date().getTime();
this.props.onClick({ts: timeStamp});
},
render: function(){
return (
React.DOM.button({onClick: this.createBox}, "createBox")
)
}
});
var app = React.createClass({
displayName: "app",
getInitialState: function() {
return {
partBoxes: []
};
},
createBox: function(partBox) {
this.state.partBoxes.push(partBox);
this.forceUpdate();
},
render: function() {
return (
React.DOM.div(null,
createBoxBtn({onClick: this.createBox}),
this.state.partBoxes.map(function(pb) {
return partBox({key: pb.ts, ts: pb.ts});
})
)
);
}
});
React.renderComponent(app(null), $main);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.