Refs trong ReactJS.
Mã nguồn tham khảo:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Refs</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(); } } }); ReactDOM.render( <div> <Comment>Hey, my name is Hao!</Comment> <Comment>Holla my name!</Comment> <Comment>Wtf?</Comment> </div> , document.getElementById('example')); </script> </body> </html>