【问题标题】:Conditional render, having an onClick determine what state is passed to a Component条件渲染,通过 onClick 确定传递给组件的状态
【发布时间】:2018-09-22 20:45:00
【问题描述】:

在我的主要组件 Game 中,它包含两个状态属性,即卡片数组 easyCards 和 hardCards,我渲染了两个 Button 组件。 Button 组件是展示性的,它们只是呈现传入的道具。我正在尝试根据我单击的按钮来确定,如何将两个卡片数组之一作为道具传递给 Card 组件以呈现它们?

handleEasyCards() {
 }
handleHardCards() {
 }


render() {

return (
  <div>
    <Timer />
    <div>
      <Button difficulty={this.state.easyButton} onClick={this.handleEasyCards}/>
      <Button difficulty={this.state.hardButton} onClick={this.handleHardCards}/>
    </div>

    <Card cardTypes={ // I want to pass a specific state property here} />

  </div>
  );
 }
}

这应该是onClick方法还是可以在render方法中处理的东西? Codesandbox

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你在正确的轨道上。从这里我可以看到的最简单的方法是:

    handleEasyCards() {
      this.setState({currentCards: this.state.easyCards});
    }
    handleHardCards() {
      this.setState({currentCards: this.state.hardCards});
    }
    

    然后在渲染中:

    <Card cardTypes={this.state.currentCards} />
    

    然后确保在currentCardsundefined 时处理Card 组件中的渲染,或者指定一个默认值。

    一个可能适用的警告,React 将优化点击相同类型的卡片,因为这将为 currentCards 分配相同的数组引用,并且它会(正确地)认为状态尚未更新。如果您想显示某种反馈(重置卡片、动画等),您需要执行以下操作:

    this.setState({currentCards: [...this.state.easyCards]});
    

    创建一个新数组来强制响应更新。

    【讨论】:

    • 所以当板子最初是空的时,我必须使用这样的静态默认 propTypes 吗? stackoverflow 我对如何渲染一个空组件有点困惑。
    • 想一想,理想情况下我想有一个空板开始,但我有应用程序设置的方式,看起来我可能需要默认为easyCards,不是吗?这是设置问题吗?
    • 不,你可以传递一个null/undefined currentCards 但你只需要在&lt;Card/&gt; 组件中处理它。这可能很简单:render() { if (!this.props.currentCards) return null; else {...} }
    • 您还可以在&lt;Game/&gt; 组件的构造函数中设置一个空数组的默认值,因此cardTypes 属性永远不会未定义。确实是个人喜好,但可能更适合您的预期设计。
    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2019-10-10
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多