问题描述
嗨,我刚刚开始使用react-bootstrap。我需要做的是循环播放电影列表,然后每一行都将显示电影细节的模式。
这是我对电影列表使用.map循环的组件:
<?PHP
// Array with names
$a[] = "one";
$a[] = "two";
$a[] = "three";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q,substr($name,$len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ",$name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
这是模态分量
{
this.state.movies
? this.state.movies.map((object,i)=>{
return (
<div obj={object.imdbID} key={i}>
<ListGroup.Item>
<Row>
<Col md={5}>
<MovieModal key={i}
onShowModal = {this.handleShowModal}
onHideModal = {this.handleHideModal}
modal = {this.state.modal}
movie = {object}
index = {i}
></MovieModal>
</Col>
<Col md={2}>{object.Year}</Col>
<Col md={3}>{object.imdbID}</Col>
<Col md={2}>
{
object.Fav
? <img src={`../assets/golden-star.png`} alt="star"></img>
: <img src={`../assets/star.png`} alt="star"></img>
}
</Col>
</Row>
</ListGroup.Item>
</div>
)
})
: <h1>not found</h1>
}
该模态已经被调用,但是对于其余的电影来说似乎是循环的。模态看起来像模态堆栈并显示最后一个模态。这是当我单击模式触发器时的控制台显示。
<div>
<p onClick={this.props.onShowModal}>{this.props.movie.Title} {this.props.index}</p>
<Modal show={this.props.modal} onHide={this.props.onHideModal} backdropClassName={'modal-backdrop'}>
<Modal.Header closeButton>
<Modal.Title>{this.props.movie.Title} {this.props.index}</Modal.Title>
</Modal.Header>
<Modal.Body>
<h1>test body</h1>
</Modal.Body>
<Modal.Footer>
<h1>test footer</h1>
</Modal.Footer>
</Modal>
</div>
解决方法
如果我的理解正确,那么您需要一个显示电影列表的模式。
您的代码创建了多个模态,因为您正在每个循环上渲染影片模态。
反过来试试。将列表嵌入到模式中。
const movies = {} // I'm assuming you have your movies object in a const
// use object deconstruction to create a list of ListGroup.Items
const MovieList = ({ movies }) =>
movies.map( (movie,index) => (
<ListGroup.Item key={movie.imdbID}>
<Row>
<Col md={2}>{movie.Year}</Col>
<Col md={3}>{movie.imdbID}</Col>
</Row>
</ListGroup.Item>
));
... render ( ...
<div>
<p onClick={this.props.onShowModal}>{this.props.movie.Title} {this.props.index}</p>
<Modal show={this.props.modal} onHide={this.props.onHideModal} backdropClassName={'modal-backdrop'}>
<Modal.Header closeButton>
<Modal.Title>{this.props.movie.Title} {this.props.index}</Modal.Title>
</Modal.Header>
<Modal.Body>
<ListGroup> {/* <----- put your list const here */}
<MovieList movies={movies} />
</ListGroup>
</Modal.Body>
<Modal.Footer>
<h1>test footer</h1>
</Modal.Footer>
</Modal>
</div>