Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. class Book extends React.Component{
  2. render()
  3. {
  4. const contacts = this.props.contacts.map(
  5. (contact,id)=>{
  6. return(
  7. <li key={id}> | {contact.name} : {contact.tel}</li>
  8. )
  9. });
  10.  
  11. return(<ol>{contacts}</ol>)
  12. }
  13. }
  14.  
  15. class Form extends React.Component {
  16. constructor(props) {
  17. super(props);
  18.  
  19. this.state = {
  20. contact: {
  21. name: '',
  22. tel: ''
  23. }
  24. };
  25. }
  26.  
  27. handleChange = e => {
  28. const target = e.target;
  29. const name = target.name;
  30. const value = target.value;
  31.  
  32. this.setState({
  33. contact:{
  34. ...this.state.contact,
  35. [name]: value
  36. }
  37. },()=>{console.log(this.state.contact.name+" "+this.state.contact.tel);});
  38.  
  39.  
  40. }
  41.  
  42. render() {
  43. return (
  44. <form onSubmit={() => this.props.addContact(this.state.contact)}>
  45. <input value={this.state.contact.name} type="text" name="name" onChange={this.handleChange} />
  46. <input value={this.state.contact.tel} type="text" name="tel" onChange={this.handleChange} />
  47. <button className="submit">OK</button>
  48. </form>
  49. );
  50. }
  51. }
  52.  
  53.  
  54. class App extends React.Component{
  55. constructor(props)
  56. {
  57. super(props);
  58. this.state={
  59. contacts: [
  60. {
  61. name: 'Jan',
  62. tel: '123 456 789'
  63. },
  64. {
  65. name: 'Krzyś',
  66. tel: '098 765 432'
  67. }
  68. ]
  69. }
  70. }
  71.  
  72. addContact(contact)
  73. {
  74. const tempContacts = this.state.contacts.concat([
  75. {
  76. name: contact.name, //Czyli tu powinien rozrzerzyć tablicę o dodatkowy obiekt z nowymi wartościami
  77. tel: contact.tel
  78. }
  79. ])
  80.  
  81. this.setState(
  82. {
  83. contacts: tempContacts, //I tu zastąpić starą tablicę, nową bogatszą o element
  84. },
  85. )
  86.  
  87. }
  88.  
  89. render()
  90. {
  91. console.log(this.state.contacts)
  92. return(
  93. <div>
  94. <Form addContact={(contact) => this.addContact(contact)}/>
  95. <div>
  96. <Book contacts={this.state.contacts}/>
  97. </div>
  98. </div>
  99. )
  100. }
  101. }
  102.  
  103. ReactDOM.render(<App />, document.getElementById('root'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement