gpt4 book ai didi

javascript - React 在 return 中调用函数来插入组件

转载 作者:行者123 更新时间:2023-12-01 01:44:35 26 4
gpt4 key购买 nike

我试图在我的类中创建一个函数,以避免多次编写相同的代码。目前我有 3 个书架,并且必须在书架标签之间编写相同的代码 3 次。我希望能够调用函数来使代码看起来更精简。这是我当前的 1 Bookshelf 代码,运行良好:

class BookApp extends React.Component {
render() {
return (
<div>
<Bookshelf shelfTitle={'Currently Reading'}>
**{this.state.allBooks.filter((book) => {
return book.shelf === 'currentlyReading';
}).map((b) => {
return (
<Book
key={b.id}
currentShelf={b.shelf}
clicked={(event) => {this.moveHandler(event, b.id)}}
bookTitle={b.title}
bookAuthor={b.authors}
backgroundImage={`url(${b.imageLinks.thumbnail})`}
/>
)
})}**
</Bookshelf>
</div>
)
}
}

我尝试添加一个执行相同操作的函数并在 { } 内调用该函数,但它不会返回我的组件。非常感谢任何帮助!

class BookApp extends React.Component {

filterBooks(shelf) {
this.state.allBooks.filter((book) => {
return book.shelf === shelf;
}).map((b) => {
return (
<Book
key={b.id}
currentShelf={b.shelf}
clicked={(event) => {this.moveHandler(event, b.id)}}
bookTitle={b.title}
bookAuthor={b.authors}
backgroundImage={`url(${b.imageLinks.thumbnail})`}
/>
)
})
}

render() {
return (
<div>
<Bookshelf shelfTitle={'Currently Reading'}>
{this.filterBooks('currentlyReading')}
</Bookshelf>
<Bookshelf shelfTitle={'Want to Read'}>
{this.filterBooks('wantToRead')}
</Bookshelf>
<Bookshelf shelfTitle={'Read'}>
{this.filterBooks('read')}
</Bookshelf>
</div>
)
}

}

最佳答案

请检查我编辑的代码。只需从 filterBooks 函数返回 filterList 集合即可。

class BookApp extends React.Component {

filterBooks(shelf) {
let filterList = this.state.allBooks.filter((book) => {
return book.shelf === shelf;
}).map((b) => {
return (
<Book
key={b.id}
currentShelf={b.shelf}
clicked={(event) => {this.moveHandler(event, b.id)}}
bookTitle={b.title}
bookAuthor={b.authors}
backgroundImage={`url(${b.imageLinks.thumbnail})`}
/>
)
})
return filterList;
}

render() {
return (
<div>
<Bookshelf shelfTitle={'Currently Reading'}>
{this.filterBooks('currentlyReading')}
</Bookshelf>
<Bookshelf shelfTitle={'Want to Read'}>
{this.filterBooks('wantToRead')}
</Bookshelf>
<Bookshelf shelfTitle={'Read'}>
{this.filterBooks('read')}
</Bookshelf>
</div>
)
}

}

关于javascript - React 在 return 中调用函数来插入组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com