将道具和状态传递给子组件

Passing props and state to child component

我正在尝试分解我的应用程序中的组件,但是 运行 在理解如何将状态和道具从我的父组件传递到子组件时遇到了一些麻烦。对于上下文,我的子组件是一个 table ,它在行中呈现一个较小的组件。

现在我有一个名为 BookComponents 的常量,它接受 Book 并写入状态。我卡住的地方是将状态和道具传递到我的 BookTable 组件中,这样我就可以在书中呈现书籍 table 而不是在主页中。感谢您提前提供帮助和提示。

主页:

import React from 'react';
import type { User, BookType } from '/types';
import Book from './Book';
import BookTable from './BookTable';

type Props = {};

type State = {
  selectedUser: <User> | null,
  books: BookType[]
};

export default class BookPage extends React.PureComponent<Props, State> {
  const BookComponents = this.state.book.map((book) => <Book {...book} />);
  const selectedUser = this.state.selectedUser;

  return (
  <div>

    <div>
      Find Users and their Books
      <Selector
        input={{
          onChange: this.onSelect,
          value: selectedUser,
        }}
        getValue={(user) => user.full_name}
      />

      {selectedUser && (
      <Section>
        <H1>
          {selectedUser.full_name}'s Books
        </H1>
        {BookComponents}
        <BookTable/>
      </Section>)}
    </div>
  </div>
  )
}

书桌代码:

import React from 'react';
import type { User } from '/types';

type Props = {};

type State = {};

export default class BookTable extends React.PureComponent<Props, State> {
  render() {
  return (
    <Section>
      <H1>
        Print User's books here
      </H1>
    </Section>
  );
 }
}

如果我没理解错的话,你只是想将状态传递给组件的道具,没有别的?

在 MainPage 的渲染中:

<BookTable books={this.state.book} />

在书桌中:

type Props = {
  books: BookType[]
};

export default class BookTable extends React.PureComponent<Props, State> {

  static defaultProps = {
    books: []
  }

  render() {
  return (
    <Section>
      <H1>
        {this.props.books.map((book) => <Book {...book} />)}
      </H1>
    </Section>
  );
 }
}

尝试像这样从父组件向子组件传递 state 和 props。

在父组件中,将值传递给子组件。

<BookTable stateaData={this.state} propsData={this.props}/>

在子组件中,获取上面的props如下。

this.props.stateaData
this.props.propsData