javascript - React,根据父组件和两个子组件之间的通信有条件地渲染组件

标签 javascript reactjs components

我对 React 有点陌生,我想做的是这个,我有一个承载状态的父组件,以及两个被认为是所谓的演示组件的子组件,可以说 (X ,Y)。 因此,组件 X 从父级接收一组 Items 作为 Prop 并渲染它,现在,应该在 X 组件中的其中一个 Items 上触发该事件,然后onClick函数将被触发,将Item.id返回给父级,然后父级将过滤状态中的项目并将选定的项目传递给组件Y,现在我希望当且仅当它成功从父项接收到所选项目时才渲染 Y,这是我的代码。

// PARENT COMPONENT
class Main extends Component {

  constructor(props) {
    super(props);

    this.state = {
      dishes: DISHES,
      selectedDish: null
    }
  }

  onDishSelect(dishId){
    this.setState({ selectedDish : dishId })
  }

  render() {
    return (
      <div >
       <Navbar dark color="secondary" >
        <div className="container">
          <NavbarBrand href="/">My Brand</NavbarBrand>
        </div>
       </Navbar>
       <Menu dishes={this.state.dishes}
            onClick={(dishId) => this.onDishSelect(dishId)} />
       <DishDetails dish={this.state.dishes.filter(dish => dish.id === this.state.selectedDish)[0]} />
      </div>
    );
  }
}

组件X

render() {
        const menu = this.props.dishes.map(item => {
            return (
                <div key={item.id} className="col-12 col-md-5 offset-md-1 mt-3">
                    <Card onClick={() => this.props.onClick(item.id)}>
                        <CardImg width="100%" src={item.image} alt={item.name} />
                        <CardImgOverlay  className="ml-5">
                            <CardTitle >{item.name}</CardTitle>
                        </CardImgOverlay>
                    </Card>
                </div>
            )
        });

        return (
            <div className="container">
                <div className="row">
                    { menu }
                </div>
               
            </div>
        );
    }

最后组成Y

class DishDetails extends Component {
    constructor(props) {
        super(props)
    }

    renderCard(dish) {
       if(this.props.dish){
        return (
            <div className="col-12 col-md-5 offset-md-1 mt-5 ">
                <Card>
                    <CardImg width="100%" src={dish.image} alt={dish.name} />
                    <CardBody>
                        <CardTitle>{ dish.name }</CardTitle>
                        <CardText>{ dish.description }</CardText>
                    </CardBody>
                </Card>
            </div>
        )
       } else {
           return(<div></div>)
       }
    }

    renderViews(review){
       if(this.props.dish){
        return(
            <div key={review.id} className="col-12 col-md-5 mt-5">
                <Media body className="mt-2">
                    <p>{review.comment}</p>
                    <p>{ review.author }, {new Intl.DateTimeFormat('en-US',{year: 'numeric', month:'short', day: '2-digit'}).format(new Date(Date.parse(review.date)))}</p>
                </Media>
            </div>
        )
       } else {
           return(<div></div>)
       }
    }



    render(){
        return(
            <div className="row">
                { this.renderCard(this.props.dish) }
                { this.renderViews(this.props.dish.comments) }
            </div>
        )
        
    }
}

我知道代码结构非常困惑,我现在只是更关心功能,提前致谢。

最佳答案

您可以在 https://reactjs.org/docs/conditional-rendering.html 找到有关条件渲染的文档。

这适用于您的代码,如下所示

// PARENT COMPONENT
class Main extends Component {

  constructor(props) {
    super(props);

    this.state = {
      dishes: DISHES,
      selectedDish: null
    }
  }

  onDishSelect(dishId){
    this.setState({ selectedDish : dishId })
  }

  render() {
    return (
      <div >
       <Navbar dark color="secondary" >
        <div className="container">
          <NavbarBrand href="/">My Brand</NavbarBrand>
        </div>
       </Navbar>
       <Menu dishes={this.state.dishes}
            onClick={(dishId) => this.onDishSelect(dishId)} />
         {this.state.selectedDish !== null &&
          <DishDetails dish={this.state.dishes.filter(dish => dish.id === this.state.selectedDish)[0]} />
         }
      </div>
    );
  }
}

这样,只有当 this.state.selectedDish 不为 null 时,才会评估 DishDetails,例如当来自 X 的事件被处理时

关于javascript - React,根据父组件和两个子组件之间的通信有条件地渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253667/

相关文章:

javascript - 进入下一个按钮链

javascript - AngularJS ui-router 带有可选查询参数的状态

javascript - Next JS 在重写中使用查询参数作为变量

delphi - 为什么我在 IDE 中得到了另一个尺寸的组件?

javascript - React 同级组件之间的状态泄漏

java - 如何将 MouseListener 留在 ChildComponent 上,但正确跟踪父组件上的鼠标进入和退出?

javascript - 可以将 Fetch API 用作请求拦截器吗?

javascript - 将表单数据发送到按钮提交的弹出窗口

javascript - 获取异步 TreeView 数据

javascript - 按两项过滤 react-instantsearch