【问题标题】:how to replace this code snippet to not use attrs? react and emotion/styled如何替换此代码段以不使用 attrs?反应和情绪/风格
【发布时间】:2024-05-29 17:35:01
【问题描述】:

我在 react 中创建一个复选框组件并使用样式化组件,如何替换此代码以不使用 attrs?

export const HiddenCheckbox = styled.input.attrs({type: 'checkbox'})`
    overflow: hidden;
    white-space: nowrap;
    width: 1px;
    height: 1px;
    margin: -1px;
    padding: 0;
`;

我的主要:

return (
    <CheckboxContainer checked={checked} onClick={handleCheckboxChange}>
      <HiddenCheckbox onChange={handleCheckboxChange} checked={checked}/>
      <StyledCheckbox checked={checked}>
        <Icon/>
      </StyledCheckbox>
      <Text checked={checked}>{children}</Text>
    </CheckboxContainer>
);

【问题讨论】:

  • 所以要去掉 HiddenCheckbox 的 type 参数?

标签: javascript reactjs typescript styled-components emotion


【解决方案1】:

你可以在渲染时直接将props添加到组件中,而不是提供额外的props

export const HiddenCheckbox = styled.input`
    overflow: hidden;
    white-space: nowrap;
    width: 1px;
    height: 1px;
    margin: -1px;
    padding: 0;
`;

return (
    <CheckboxContainer checked={checked} onClick={handleCheckboxChange}>
      <HiddenCheckbox type="checkbox" onChange={handleCheckboxChange} checked={checked}/>
      <StyledCheckbox checked={checked}>
        <Icon/>
      </StyledCheckbox>
      <Text checked={checked}>{children}</Text>
    </CheckboxContainer>
);

【讨论】:

    最近更新 更多