【问题标题】:Toggling button state and reusing toggle function for other buttons切换按钮状态并为其他按钮重用切换功能
【发布时间】:2017-11-05 07:40:35
【问题描述】:

我有四个按钮组件,我想为其切换一个主要的道具组件,而主要的道具只是一个真/假输入。如果为 true,它将按钮颜色更改为紫色,如果为 false,则为灰色。目前,我知道如何做到这一点的唯一方法是创建一个新的 toggleProfitView 函数,该函数明确声明 setState({revenueb: !this.state.revenueb}),另一个声明 setState({profitb: !this.state.profitb}),但我有四种不同的按钮状态,我想要能够重用一个知道要切换哪个按钮的功能。我正在尝试对我的代码进行干燥。在伪代码中它会是这样的,

this.button.primary.state = !this.button.primary.state

有什么想法吗?谢谢。

toggleProfitView(key, event) {
    console.log(event)
    var plot_number = this.state.plot_number
     this.setState({variant_plot_data: this.props.final_plot[plot_number]}, () => {
      this.updatePlots(key);
    });
  }

function PlotIfDataExists(props) {
  const dataExists = props.dataExists;
  if(dataExists) {
    return (<div>
              <ProductGraphData variant_plot_data = {variant_plot_data} />
              <Stack spacing="none" distribution="leading">
                <Select
                  options={props.variants}
                  placeholder="Select"
                  onChange={props.handleVariantChange}
                />
                <Button onClick={props.toggleVariantPlotData}>Next Plot</Button>
                <Button primary={props.revenueb} onClick={(event) => props.toggleView('revenue', event)}>Revenue Plot</Button>
                <Button primary={props.profitb} onClick={(event) => props.toggleView('profit', event)}>Profit Plot</Button>
                <Button primary={props.profitvb} onClick={(event) => props.toggleView('profit_per_view', event)}>Profit/View Plot</Button>
                <Button primary={props.revenuevb} onClick={(event) => props.toggleView('rev_per_view', event)}>Rev/View Plot</Button>
                <Button onClick={props.showAllPlots}>Show All</Button>
              </Stack>
              <LastPriceTestContainer analytics_data = {variant_plot_data} />
            </div>
    );
  }
  return null;
}

【问题讨论】:

  • 如果我理解正确的话,一个自定义按钮组件如何管理它自己的颜色状态 onClick。如果父母需要知道任何事情,您仍然可以调用父母传入的 onClick。

标签: javascript reactjs


【解决方案1】:

我使用哈希解决了这个问题来维护状态。

 toggleView(key, event) {
    const button_states_hash = Object.assign({}, this.state.button_states);
    button_states_hash[key] = !button_states_hash[key]
    var plot_number = this.state.plot_number
     this.setState({
       variant_plot_data: this.props.final_plot[plot_number],
       button_states: button_states_hash
     }, () => {
      this.updatePlots(key);
    });
  }

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    相关资源
    最近更新 更多