我正在尝试构建一个简单的应用程序,从谷歌图书API获取书籍。我有一个带有搜索栏的Body组件,它呈现了一个BookDisplay
组件,该组件将一系列书籍映射到BookCard
s中。每张卡都有一个Learn More
按钮,它应该打开一个包含所有书籍信息的模态,这就是我遇到的问题。如何将图书信息传递给BookModal
组件?这是我实际的BookDisplay类的一个例子
import style from './booksdisplay.module.css'
import BookCard from "../BookCard/BookCard";
import BookModal from "../BookModal/BookModal";
function BooksDisplay(props) {
const books=props.books
if(books.length===0){
return(
<div>{props.message}</div>
)
}
else{
return (
<div className='Books'>
<div>{props.message}</div>
{
books.map(book=>{
return (
<BookCard data={book.volumeInfo}/>
)
})
}
<BookModal/>
</div>
)
}
}
export default BooksDisplay
这是我的图书卡类
import {Button, Card, CardBody, CardHeader, CardImg, CardSubtitle, CardTitle} from "shards-react";
const BookCard=(props)=> {
function normalizeAuthors(arr) {
if(!arr)
{
arr=['no authors']
}
return arr;
}
return(
<Card style={{maxWidth:'300px'}}>
<CardHeader>
<CardTitle>{props.data.title}</CardTitle>
<CardSubtitle>{normalizeAuthors(props.data.authors)}</CardSubtitle>
</CardHeader>
<CardBody>
<CardImg src={props.data.imageLinks}/>
<Button outline >Learn More</Button>
</CardBody>
</Card>
)
}
export default BookCard
您只需要让父级知道;了解更多";按钮。
例如:
function BooksDisplay(props) {
const [selectedbook, setSelectedBook] = React.useState();
const handleClick = (book) => {
// save this book in the state
setSelectedBook(book);
};
const books = props.books;
if (books.length === 0) {
return <div>{props.message}</div>;
} else {
return (
<div className="Books">
<div>{props.message}</div>
{books.map((book) => {
return (
<BookCard
clicked={() => handleClick(book)}
data={book.volumeInfo}
/>
);
})}
// In the `BookModal` component you can use the `bookData` prop.
<BookModal bookData={selectedbook} />
</div>
);
}
}
在BookCard
组件中:
const BookCard = (props) => {
function normalizeAuthors(arr) {
if (!arr) {
arr = ["no authors"];
}
return arr;
}
return (
<Card style={{ maxWidth: "300px" }}>
<CardHeader>
<CardTitle>{props.data.title}</CardTitle>
<CardSubtitle>{normalizeAuthors(props.data.authors)}</CardSubtitle>
</CardHeader>
<CardBody>
<CardImg src={props.data.imageLinks} />
<Button outline onClick={props.clicked}>
Learn More
</Button>
</CardBody>
</Card>
);
};