首页 > 解决方案 > 如何在另一个组件的函数中渲染反应组件?

问题描述

所以我需要渲染“警报”组件,它通知用户组件中的成功操作 - 内部函数,它将项目添加到购物车/本地存储。

报警组件:

class Alarm extends React.Component{

    render(){
        return(
                <Alert color="success">
                This is a success alert — check it out!
                </Alert>
        )
    }
}

另一个组件中的功能:

addToCart = () => {
  (Some Logic...)
}

编辑

我有 2 个组件:

初始化函数 addToCard 后,我需要渲染警报组件


解决方案

我在构造函数状态中声明“x”:

constructor(props) {
    super(props);
    this.state = {
        quantity: 1,
        x: false
    }
}

并添加到 ProductItem 组件:

<div>
    { this.state.x &&
      <Alarm />
    }      
  </div>

而内部函数只是:

this.setState({x: true})

标签: reactjsfunctionrendering

解决方案


'Standard comunication'react 中的组件之间是通过将 props 从父级传递给子级来完成的(即使是几级深)。阅读文档。可以使用 redux、上下文 API、apollo 等来部署通用/应用范围的状态。

在这种情况下,您可能需要使用门户


推荐阅读