[英]Passing props and state to child component
我試圖在我的應用程序中分解組件,但在理解如何將 state 和道具從我的父組件傳遞到子組件時遇到了一些麻煩。 對於上下文,我的子組件是一個表格,它在行中呈現一個較小的組件。
現在我有一個名為 BookComponents 的常量,它接收一本書並寫入 state。 我被卡住的地方是將 state 和道具傳遞到我的 BookTable 組件中,以便我可以在書表中而不是在主頁中呈現書籍提前感謝您的幫助和提示。
主頁:
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>
);
}
}
如果我理解正確,您只想將 state 傳遞給組件的道具,僅此而已?
在 MainPage 的渲染中:
<BookTable books={this.state.book} />
在 BookTable 中:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.