【问题标题】:Saving the state of the button onClick保存按钮 onClick 的状态
【发布时间】:2022-02-06 00:01:21
【问题描述】:

我有:

<blink>

  const [thisButtomSelected, setThisButtomSelected] = useState(false);
  var thisButton = [];

  const onAttributeClick = (e) => {
    thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e.currentTarget.name }
    setThisButtomSelected(thisButton[e.currentTarget.value]);
  }
  return(
    <div>
      {data.item.attributes.map((attribute, index) => (
        <div key={index} >
          <p id={attribute.id}>{attribute.name}:</p>

          <ul className="choose-attribute-container-ul">
            {attribute.items.map((item) => (

              <li key={item.id}>
                <button
                  value={item.value}
                  id={item.id}
                  name={attribute.name}
                  className={_.isEqual(thisButtomSelected, { thisID: item.id, thisName: attribute.name }) ? 'attribute-button-selected' : 'attribute-button'}
                  onClick={onAttributeClick}
                >
                  {item.displayValue}
                </button>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  )

</blink>

这种模式可以正常工作,但是每当页面上的属性超过 1 个并且用户选择的属性超过一个时,之前选择的按钮就会被取消点击。
我的问题是:单击第二个按钮后如何保存第一个选定按钮的状态?

  1. 每个属性只能激活一个按钮
  2. 应使用按钮名称

【问题讨论】:

  • 如果你想要多个选择然后在thisButtomSelected中创建一个数组并将点击的id保存在状态中,并在类名中检查某个按钮的id是否存在。

标签: javascript reactjs graphql apollo-client


【解决方案1】:

您应该将按钮保存在一个数组中以保留它们,就像这样:

  const [thisButtomSelected, setThisButtomSelected] = useState([]);

  var thisButton = [];
  
  const onAttributeClick = (e) => {
      thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e.currentTarget.name }
  
      setThisButtomSelected([...thisButtomSelected, thisButton[e.currentTarget.value]]);
  
  }
  return(
              <div>
                  {data.product.attributes.map((attribute, index) => (
                      <div key={index} >
                          <p id={attribute.id}>{attribute.name}:</p>
  
                          <ul className="choose-attribute-container-ul">
                              {attribute.items.map((item) => (
  
                                  <li key={item.id}>
                                      <button
                                          value={item.value}
                                          id={item.id}
                                          name={attribute.name}
                                          className={thisButtomSelected.find(el => el.thisID === item.id && el.thisName === attribute.name) ? 'attribute-button-selected' : 'attribute-button'}
                                          onClick={onAttributeClick}
                                      >

【讨论】:

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