Multiple Child Components trong ReactJS.
Mã nguồn tham khảo:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Multiple Child Components</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://npmcdn.com/[email protected]/dist/react.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-dom.min.js"></script>
<script src="https://npmcdn.com/[email protected]/browser.min.js"></script>
<style type="text/css">
.mb5px {
margin-bottom: 5px
}
</style>
</head>
<body style="padding:20px">
<div id="example"></div>
<script type="text/babel">
var Comment = React.createClass({
getInitialState: function() {
return {editing: false}
},
edit: function() {
this.setState({editing: true});
},
save: function() {
var val = this.refs.newText.value;
console.log("New comment: " + val);
this.setState({editing: false});
},
remove: function() {
console.log("Removing Comment!");
},
renderNormal: function() {
return (
<div className="media">
<div className="media-body">
<h4 className="media-heading">{this.props.children}</h4>
<button onClick={this.edit} className="btn btn-primary">Edit</button>
<button onClick={this.remove} className="btn btn-danger">Remove</button>
<hr />
</div>
</div>
);
},
renderForm: function() {
return (
<div className="media">
<div className="media-body">
<textarea ref="newText" className="form-control mb5px">{this.props.children}</textarea>
<button onClick={this.save} className="btn btn-success">Save</button>
<hr />
</div>
</div>
);
},
render: function() {
if (this.state.editing) {
return this.renderForm();
} else {
return this.renderNormal();
}
}
});
var Board = React.createClass({
getInitialState: function() {
return {
comments: [
'Yeah yeah!',
'Hell yeah!',
'Aw yeah!'
]
};
},
render: function() {
return (
<div>
{
this.state.comments.map(function(text, i) {
return (<Comment key={i}>{text}</Comment>);
})
}
</div>
);
}
});
ReactDOM.render(<Board />, document.getElementById('example'));
</script>
</body>
</html>
Không có bình luận.