如何在 ReactJS 中组件间传递状态
由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!
在这篇文章中,我将解释如何在 Reactjs 中组件之间传递状态。
我们将构建一个简单的“你读了多少本书?”应用。在这个应用中,我们
有两个主要组件:一个较大的组件名为“图书馆”,另一个较小的组件名为“书籍”。图书馆状态中有 3 本书,每本书都有自己的状态。选中任何一本书即可将其计入已读状态。点击此处体验应用。
让我们从代码开始:
将状态从父级传递给子级
在我们的库组件中,我们有以下状态
this.state = {
reads: 0,
books: [
{
name: 'Zero to one',
isbn: '9780804139298',
author: 'Peter Thiel',
cover: 'https://images.gr-assets.com/books/1414347376l/18050143.jpg',
status: false
},
{
name: "The Manager's Path",
isbn: '9781491973899',
author: 'Camille Fournier',
cover: 'https://images.gr-assets.com/books/1484107737l/33369254.jpg',
status: false
},
{
name: 'Calculus, Better Explained',
isbn: '9781470070700',
author: 'Kalid Azad',
cover: 'https://images.gr-assets.com/books/1448590460l/27993945.jpg',
status: false
}
]
};
我们希望创建this.state.books.length多个组件,每个组件都拥有来自其状态数组的Bookprops 。我们需要处理这两个组件。booksLibrary
首先,对于父组件,我们需要创建多个Book组件,并将不同的值传递给它们,就像这样:this.state.books.length
{
this.state.books.map((_book, _id) => {
return (
<Book
handleCounter={this.handleCounter}
key={_id}
id={_book.isbn}
name={_book.name}
isbn={_book.isbn}
author={_book.author}
cover={_book.cover}
/>
);
});
}
handleCounter暂时忽略此提示。
其次,对于子节点Book,我们已经有了父节点的值,让我们使用这些值:
...
render() {
return (
<Card>
<Image
src={this.props.cover}
alt="Book cover"
...
到目前为止,我们已经Book从父组件创建了 3 个子组件Library,并从父组件的状态设置了它们的值。
很简单,对吧?
很好,让我们开始第二部分。
将状态从子女传递给父母
在本节中,我们希望通过勾选每本书的复选框来处理您阅读的书籍数量。
在我们的Book国家,我们有这种状态
this.state = {
status: false,
id: this.props.id
};
注意:不要忘记将其传递props给组件的构造函数。
status表示你是否读过这本书,其默认值为false,id是这本书的 ID,我根据书的 ID 来设置它,就像我们在上一节中学到的那样。
我们需要处理此状态的更改,然后更新父状态中的 books 数组。
在我们的Book组件中,我们将添加一个复选框,用于接收书籍状态的更改并将其传递this.handleChange给其onChange事件,如下所示:
<input type="checkbox" name="example" onChange={this.handleChange} />
你需要先绑定函数,然后Book用新的状态更新状态,更新子状态后,我们再更新父状态,Library像这样:
handleChange() {
this.setState({status: !this.state.status}, this.updateLibraryCount);
}
updateLibraryCount() {
this.props.handleCounter(this.state);
}
我们updateLibraryCount使用handleCounter函数Library作为 prop,然后将Book状态传递给它,现在可以Library看到Book状态了,太好了!让我们使用它。
handleCounter(_State) {
//Get the index of this book by searching by its unique isbn
const ObjNum = this.state.books.findIndex(
_book => _book.isbn === _State.id
);
//then update its value in the Library component
this.setState(
{
books: update(
ObjNum,
{...this.state.books[ObjNum], status: _State.status},
this.state.books
)
},
() => {
//this is a callback to handle the new change of the book status and increment the reads
const _read = this.state.books.filter(_book => _book.status === true)
.length;
this.setState({reads: _read});
}
);
}
我希望您能理解如何在父组件和子组件之间传递状态。这是完整的代码,这是我博客上的原文。如果您有任何疑问,欢迎在评论区留言或发送邮件。
文章来源:https://dev.to/zeyadetman/how-to-pass-state- Between-components-in-reactjs-2pg1