如何替换此代码段以不使用 attrs?反应和情绪/风格

Posted

技术标签:

【中文标题】如何替换此代码段以不使用 attrs?反应和情绪/风格【英文标题】:how to replace this code snippet to not use attrs? react and emotion/styled 【发布时间】:2021-07-09 10:15:59 【问题描述】:

我在 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 参数? 【参考方案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>
);

【讨论】:

以上是关于如何替换此代码段以不使用 attrs?反应和情绪/风格的主要内容,如果未能解决你的问题,请参考以下文章