【问题标题】:how to access value of state of Root Component in the child component如何在子组件中访问根组件的状态值
【发布时间】:2019-01-17 06:34:16
【问题描述】:

我创建了一个 React 应用程序。在这个应用程序中,我创建了以下组件:

  • 应用组件(根):数据加载到状态的位置
  • CardList 组件:卡片列表,数据通过 props 传递给它
  • Card 组件:使用 forEach 向 Card 传递数据,它有按钮
  • CustomButton 组件:就像一个带有样式的按钮

我想要的是当用户点击任何卡片上的按钮时,每次都应该增加一个数字。但我无法在此处访问数据。

谁能帮忙?

这是供您参考的卡片组件:

class Card extends Component {

render() {
    return (
        <div className="tc bg-light-green dib br3 pa3 ma2 grow bw2 shadow-5">
            <h2>Votes: {this.props.votes}</h2>
            <div>
                <img src={this.props.pic} alt='Superstar'/>
                <div>
                    <h2>{this.props.name}</h2>
                    <p>{this.props.email}</p>
                </div>
            </div>
            <ActionButton btnText="Vote Now!" clickhandler={this.onVoteButtonClick}/>
        </div>
    );
}
onVoteButtonClick = (event) => {
    console.log('It was clicked : '+this.props.id);      
}

}

【问题讨论】:

  • 如果您不想通过三个组件中的道具向下传递函数,您可以使用context

标签: javascript reactjs


【解决方案1】:

您应该更多地研究两个选项,以了解最适合您需要的选项:

  1. Redux(或类似的)
  2. React 16 中提供了新的 Context API

这两种解决方案的要点是,您可以独立于依赖的组件树来管理应用程序状态。 Context API 可以说更容易实现,而您目前会发现更多解释 Redux 方法的示例,因为它仍然是目前最常见的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2018-09-08
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多