react : update parent state from within child

  1. var Child = React.createClass({
  2. handleClick: function(event){
  3. if (confirm("Press a button!")) {
  4. this.props.sendChildConfirm();
  5. } else {
  6. this.props.sendChildCancel();
  7. }
  8. }
  9. ,
  10. render: function () {
  11. return (
  12. <a style={{border: 1}} onClick={this.handleClick}>update parent state from within child</a>
  13. );
  14. },
  15. });
  16. var Parent = React.createClass({
  17. getInitialState: function() {
  18. return {childText: 'Nothing'};
  19. },
  20. render: function () {
  21. return (
  22. <div>
  23. <h3>Child says {this.state.childText}</h3>
  24. <Child sendChildConfirm={this.handleConfirm} sendChildCancel={this.handleCancel} />
  25. </div>
  26. );
  27. },
  28. handleConfirm: function(event) {
  29. this.setState({childText: 'Yes!'});
  30. },
  31. handleCancel: function(event) {
  32. this.setState({childText: 'No!'});
  33. }
  34. });
  35. ReactDOM.render(
  36. <Parent />,
  37. document.getElementById('react-child-parent-dom-node')
  38. );

Download full working code : Download

No comments:

Post a Comment