使用来自其他组件的值设置状态

时间:2018-12-29 22:55:23

标签: javascript reactjs

我的App.js类中有一个书对象数组

{ id: 1,title: "How to Learn JavaScript - Vol 1", info: "Study hard"},
    { id: 2,title: "How to Learn ES6", info: "Complete all exercises :-)"},
    { id: 3,title: "How to Learn React",info: "Complete all your CA's"},
    { id: 4,title: "Learn React", info: "Don't drink beers, until Friday (after four)"
    }

我想制作一个新组件,可以在其中添加新的书本对象。

import React, { Component } from 'react'

export default class AddBook extends Component {

    state={
        title: '',
        info: ''
    }
  render() {
    return (
      <div>
        <input type="text" placeholder="title" value={this.state.title} onChange={(e) =>{this.setState({title: e.target.value})}}>Enter title</input>
        <input type="text" placeholder="title" value={this.state.info} onChange={(e) =>{this.setState({info: e.target.value})}}>Enter Info</input>
        <button onClick={this.props.addBook(this.state.title, this.state.info)}>Submit</button>
      </div>
    )
  }
}

我想将表单中的值传递回App.js,因此可以将对象添加到我的书本数组中。

1 个答案:

答案 0 :(得分:1)

这是您的App.js:

import React from 'react';
import Form from './Form';

export default class App extends React.Component {
  state = { books: [] };

  addBook = book => {
    this.setState({ books: [book, ...this.state.books] });
  };
  render() {
    return (
      <div>
        <Form addBook={this.addBook} />
        {this.state.books.map(book => {
          return (
            <div key={book.id}>
              <div>Title: {book.title}</div>
              <div>Info: {book.info}</div>
            </div>
          );
        })}
      </div>
    );
  }
}

这是您的Form.js:

import React from 'react';

export default class Form extends React.Component {
  state = { title: '', info: '' };

  generateId = () =>
    Math.random()
      .toString(36)
      .substr(2, 10);

  handleChange = event => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  };

  handleSubmit = event => {
    event.preventDefault();
    this.props.addBook({
      id: this.generateId(),
      title: this.state.title,
      info: this.state.info,
    });
    this.setState({ title: '', info: '' });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          name="title"
          value={this.state.title}
          onChange={this.handleChange}
        />
        <input
          type="text"
          name="info"
          value={this.state.info}
          onChange={this.handleChange}
        />
        <input type="submit" />
      </form>
    );
  }
}

尝试对其进行剖析并弄清其工作原理...如果您有疑问,请问...

相关问题