簡體   English   中英

如何在React中將多個數據作為對象從子組件發送到父組件?

[英]How can i send multiple data as an object to parent component from child component in React?

從子組件我想在父組件中傳遞一些數據。 並且基於數據還想更新父組件的狀態。 我以下面的方式嘗試。 但是每次我更改輸入字段updatedHandler()都會被調用。 本應僅在單擊按鈕時調用。

父組件:

class Blog extends Component {
state = {
    posts: [],
    selectedPostId: null
};

componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            const posts = response.data.slice(0, 3);
            const updatedPosts = posts.map((post) => {
                return {
                    ...post,
                    author: 'Tanvir'
                }
            });
            this.setState({ posts: updatedPosts })
        });
}

selectedPostHandler = (id) => {
    this.setState({ selectedPostId: id })
};

updatedPostsHandler = (post) => {
    // axios.post('https://jsonplaceholder.typicode.com/posts/', post)
    //     .then(response => {
    //     }
    // );
    console.log(post);

}

render() {
    const posts = this.state.posts.map(
        post => <Post
            key={post.id}
            title={post.title}
            author={post.author}
            clicked={() => this.selectedPostHandler(post.id)} />
    );
    return (
        <div>
            <section className="Posts">
                {posts}
            </section>
            <section>
                <FullPost id={this.state.selectedPostId} />
            </section>
            <section>
                <NewPost
                    newPostCreated={this.updatedPostsHandler} />
            </section>
        </div>
    );
}
}

子組件:

class NewPost extends Component {
state = {
    title: '',
    content: '',
    author: 'Max',
    post: ''
}

handleChange = (event) => {
    this.setState({
        [event.target.name]: event.target.value,
        post: {
            title: this.state.title,
            content: this.state.content,
            author: this.state.author
        }
    });
}

render() {
    return (
        <div className="NewPost">
            <h1>Add a Post</h1>
            <label>Title</label>
            <input type="text" name="title" value={this.state.title} onChange={this.handleChange} />
            <label>Content</label>
            <textarea rows="4" name="content" value={this.state.content} onChange={this.handleChange} />
            <label>Author</label>
            <select name="author" value={this.state.author} onChange={this.handleChange}>
                <option value="Max">Max</option>
                <option value="Manu">Manu</option>
            </select>
            <button
                onClick={this.props.newPostCreated(this.state.post)}>
                Add Post
            </button>
        </div>

    );
}

}

您需要將其編寫為:

onClick={() => this.props.newPostCreated(this.state.post)}>

否則,每次在執行setState(..)時調用render()時,它將在JSX {..}內部執行。 出於性能原因,最好沒有箭頭功能的方式編寫它。

class NewPost extends Component {
  // ..
  onBtnClick = () => {
    this.props.newPostCreated(this.state.post);
  };

  render() {
    return (
      // ..
        <button onClick={this.onBtnClick}>Add Post</button>
      </div>
    );
  }
}

我還發現您的狀態構造和handleChange函數有點奇怪和錯誤。 我將這樣編寫類:

class NewPost extends Component {
  state = {
    post: {
      title: "",
      content: "",
      author: "Max"
    }
  };

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

  onBtnClick = () => {
    this.props.newPostCreated(this.state.post);
  };

  render() {
    const { post: { content, title, author } } = this.state;
    return (
      <div className="NewPost">
        <h1>Add a Post</h1>
        <label>Title</label>
        <input
          type="text"
          name="title"
          value={title}
          onChange={this.handleChange}
        />
        <label>Content</label>
        <textarea
          rows="4"
          name="content"
          value={content}
          onChange={this.handleChange}
        />
        <label>Author</label>
        <select
          name="author"
          value={author}
          onChange={this.handleChange}
        >
          <option value="Max">Max</option>
          <option value="Manu">Manu</option>
        </select>
        <button onClick={this.onBtnClick}>Add Post</button>
      </div>
    );
  }
}

您應該將updatedPostsHandler調用作為一個函數添加到子組件。 因此,當您單擊子組件上的按鈕時,它將調用一個函數,該函數將執行一個函數。

嘗試如下添加您的updatedPostsHandler:

<NewPost newPostCreated={() => this.updatedPostsHandler} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM