【问题标题】:Styled components, toggle state with mapped buttons样式化组件,使用映射按钮切换状态
【发布时间】:2020-01-07 20:59:12
【问题描述】:

我有 4 个通过我的地图功能生成的按钮。当我单击按钮时,我希望样式仅应用于那个 1 按钮。现在该样式正在应用于所有按钮。

我哪里错了?

const MultiChoiceQuestions = props => {
  const { multiChoiceArray, handleClick, inputValue, updateInputValue } = props
  const [active, setActive] = useState(false)
  console.log('state', active)
  // () => handleClick(questionChoice)
  return (
    <ButtonContainer>
      {multiChoiceArray.map(questionChoice => {
        return (
          <Button
            active={active}
            type="button"
            key={questionChoice.id}
            onClick={() => setActive(!active)}
          >
            {questionChoice.text}
          </Button>
        )
      })}
    </ButtonContainer>
  )
}

const Button = styled.button`
  height: 3rem;
  width: 20rem;
  border-style: solid;
  border-width: 1px;
  border-color: #c7c7c76b;
  background-color: ${props => (props.active ? 'green' : 'white')};
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  border-radius: 6px;
  transition: background 250ms ease-in-out, transform 150ms ease;
  font-weight: 400;
  &:hover {
    background-color: #ff00006b;
    transform: scale(1.25);
    font-weight: 800;
    border: none;
  }
`

【问题讨论】:

    标签: javascript reactjs oop styled-components


    【解决方案1】:

    您需要将活动按钮的 ID 保持在状态。并且在渲染按钮时,检查按钮的 ID 是否等于活动 ID 状态。它将类似于单选按钮。

    const MultiChoiceQuestions = props => {
      const { multiChoiceArray, handleClick, inputValue, updateInputValue } = props
      const [activeId, setActiveId] = useState()
      console.log('state', active)
      // () => handleClick(questionChoice)
      return (
        <ButtonContainer>
          {multiChoiceArray.map(questionChoice => {
            return (
              <Button
                active={questionChoice.id === activeId}
                type="button"
                key={questionChoice.id}
                onClick={() => setActive(questionChoice.id)}
              >
                {questionChoice.text}
              </Button>
            )
          })}
        </ButtonContainer>
      )
    }
    

    【讨论】:

    • 完美!谢谢 :) 我会接受作为答案
    【解决方案2】:

    所有按钮只有一个state 变量。您可以创建一个新的按钮组件(具有自己的状态)或创建一个具有四种状态的数组。

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 2020-09-20
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多