【问题标题】:React, Conditionally rendering a component based upon communication between a parent and two children componentsReact,基于父组件和两个子组件之间的通信有条件地渲染组件
【发布时间】:2018-11-11 21:59:33
【问题描述】:

我对 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>
        )
        
    }
}

我知道代码结构很混乱,我现在只是更关心功能,在此先感谢。

【问题讨论】:

    标签: javascript reactjs components


    【解决方案1】:

    您可以在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>
        );
      }
    }

    这样,DishDetails 仅在 this.state.selectedDish 不同于 null 时才被评估,例如当来自 X 的事件被处理时

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多