我有一个react应用程序,其中我想渲染菜单项的数组,然后单击以显示展开的菜单项的描述。菜单项的数组位于单独的文件dishes.js
菜单项列表在Menu
组件中呈现。单击时,展开的菜单项通过DishDetail
组件呈现。
dishes.js
export const DISHES =
[
{...}
]
MenuComponent.js
class Menu extends Component {
constructor (props) {
super (props);
this.state = {
selectedDish: null
}
}
onDishSelect(dish){
this.setState({ selectedDish: dish })
}
render() {
const menu = this.props.dishes.map((dish)=>{
return (
<div key = {dish.id} className="col-12 col-md-5 m-1"> {/* why do we need this key attribute whenever we construct a list of items in react, we need this key attribute When rendering elements on screen, the keys help react identify these elements uniquely */}
<Card onClick = {()=>this.onDishSelect(dish)}>
<CardImg width="100%" src= {dish.image} alt = {dish.name} />
<CardImgOverlay>
<CardTitle> {dish.name} </CardTitle>
</CardImgOverlay>
</Card>
</div>
);
});
return(
<div className="container">
<div className="row">
{menu}
</div>
<div className = "row">
<DishDetail p={this.state.selectedDish} />
</div>
</div>
);
}
}
export default Menu;
DishdetailComponent.js
class DishDetail extends Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
if (p != null){
return(
<div className = "row">
<Card>
<CardImg width="100%" src={p.image} alt={p.name} />
<CardBody>
<CardTitle> {p.name} </CardTitle>
<CardText> {p.description}</CardText>
</CardBody>
</Card>
</div>
);
}
else {
return(
<div> </div>
);
}
}
}
export default DishDetail;
输出
./src/components/DishdetailComponent.js
Line 17:9: 'p' is not defined no-undef
Line 22:40: 'p' is not defined no-undef
Line 22:54: 'p' is not defined no-undef
Line 24:28: 'p' is not defined no-undef
Line 25:27: 'p' is not defined no-undef
Search for the keywords to learn more about each error.
在此问题上的任何帮助将不胜感激。
答案 0 :(得分:2)
您没有在render函数中定义p
。您可能是说this.props.p
吗?
class DishDetail extends Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
const { p } = this.props;
if (p != null){
return(
<div className = "row">
<Card>
<CardImg width="100%" src={p.image} alt={p.name} />
<CardBody>
<CardTitle> {p.name} </CardTitle>
<CardText> {p.description}</CardText>
</CardBody>
</Card>
</div>
);
}
else {
return(
<div> </div>
);
}
}
}
export default DishDetail;