【问题标题】:How to preserve props of original html element when using styled components?使用样式化组件时如何保留原始 html 元素的道具?
【发布时间】:2020-03-18 17:55:42
【问题描述】:

我发现自己处于当前情况,我有我的 Print 组件,它们是我的设计系统的基本构建块,并将 css 设置为一些规范化的样式,这里是输入示例

InputPrint.tsx

import styled from 'styled-components';
import theme from '../util/theme';

/**
 * Styles
 */
const InputPrint = styled.input`
  display: inline-block;
  appearance: none;
`;

export default InputPrint;

然后我在我的实际组件中使用这个Print

Input.tsx

import React from 'react';
import styled from 'styled-components';
import InputPrint from '../blueprints/InputPrint';

/**
 * Styles
 */
const StyledInput = styled(InputPrint)`
  width: 65vw;
  color: #797155;
`;

/**
 * Component
 */
function Input({ ...props }) {
  return (
    <StyledInput
      autoComplete="off"
      autoCorrect="off"
      autoCapitalize="off"
      spellCheck={false}
      {...props}
    />
  );
}

export default Input;

这里的问题发生在道具上,在某些组件中,我可能有额外的道具或覆盖上面的默认道具,但仍然希望将它们全部传递给有效的&lt;input /&gt; 元素道具。我尝试了两种输入方法,即

props: React.ComponentProps<typeof InputPrint>

如果我这样做 ^ 当我使用 &lt;Input /&gt; 时,我不会在道具上获得任何自动完成功能

props: React.HTMLProps<HTMLInputElement>

如果我这样做 ^ 我在下面的 Input.tsx 中为 &lt;StyledInput /&gt; 突出显示一个打字错误

const StyledInput: StyledComponent 样式

没有重载匹配这个调用。重载 1 of 2, '(props: 挑选, HTMLInputElement>, "表单" | ... 283 更多... | “步骤”> & { ...; }, "参考" | ... 284 更多... | "step"> & 部分<...>, "ref" | ... 284 更多... | “步骤”> & { ...; } & { ...; }): ReactElement<...>', 给 以下错误。 输入'{接受?:字符串|不明确的;接受字符集?:字符串 |不明确的;动作?:字符串 |不明确的; allowFullScreen?: 布尔值 | 不明确的; allowTransparency?: 布尔值 |不明确的; alt?: 字符串 | 不明确的; ... 353 更多 ...;键?:字符串 | ... 1 更多 ... | 不明确的; }' 不可分配给类型 '挑选, HTMLInputElement>, "表单" | ... 283 更多... | “步骤”> & { ...; }, "参考" | ... 284 更多... | "step"> & 部分<...>, "ref" | ... 284 更多... | “步骤”>'。 属性“ref”的类型不兼容。 键入'字符串 | ((实例:HTMLInputElement | null)=> void)|参考对象 |空 | undefined' 不可分配给 类型'((实例:HTMLInputElement | null)=> void)| 参考对象 |空 |不明确的'。 类型 'string' 不可分配给类型 '((instance: HTMLInputElement | null) => void) |参考对象 |空值 |不明确的'。重载 2 of 2, '(props: StyledComponentPropsWithAs): ReactElement<...>',给出了以下错误。 输入'{接受?:字符串|不明确的;接受字符集?:字符串 |不明确的;动作?:字符串 |不明确的; allowFullScreen?: 布尔值 | 不明确的; allowTransparency?: 布尔值 |不明确的; alt?: 字符串 | 不明确的; ... 353 更多 ...;键?:字符串 | ... 1 更多 ... | 不明确的; }' 不可分配给类型 '(IntrinsicAttributes & 挑选&偏>, 字符串 |号码 |符号> & { ...; } & { ...; }) | (IntrinsicAttributes & ... 3 更多 ... & { ...; })'。 输入'{接受?:字符串|不明确的;接受字符集?:字符串 |不明确的;动作?:字符串 |不明确的; allowFullScreen?: 布尔值 | 不明确的; allowTransparency?: 布尔值 |不明确的; alt?: 字符串 | 不明确的; ... 353 更多 ...;键?:字符串 | ... 1 更多 ... | 不明确的; }' 不可分配给类型 '{ as?: "symbol" | “对象” | 组件类 |功能组件 | “一个” | “缩写” | “地址” | “面积” | “文章” | “一边” | “音频” | ... 165 更多... |不明确的; }'。 属性“as”的类型不兼容。 键入'字符串 | undefined' 不可分配给类型 '"symbol" | “对象” |组件类 | 功能组件 | “一个” | “缩写” | “地址” | “面积” | “文章” | “一边” | “音频” | ... 165 更多... |不明确的'。 类型“字符串”不可分配给类型“符号”| “对象” |组件类 |功能组件 | “一个” | “缩写” | “地址” | “面积” | “文章” | “一边” | “音频” | ... 165 更多... |未定义'.ts(2769)

【问题讨论】:

  • 你试过使用 作为道具吗?
  • 以这种方式同时使用它们不会满足ComponentPropsHTMLProps 的要求,我认为同时使用它们会导致类似的错误?

标签: reactjs typescript styled-components


【解决方案1】:

这个问题有点老了。但它可能会帮助面临同样问题的其他人。如果您使用的是 Styled 组件,那么在这种情况下使用瞬态道具可能会有所帮助。

如果你想防止被样式化组件使用的 props 被传递到底层的 React 节点或渲染到 DOM 元素,你可以在 props 名称前加上美元符号 ($),把它变成瞬态道具。

const Comp = styled.div`
  color: ${props =>
    props.$draggable || 'black'};
`;

render(
  <Comp $draggable="red" draggable="true">
    Drag me!
  </Comp>
);

【讨论】:

    【解决方案2】:

    我像这样导出默认样式的组件:

    import styled from 'styled-components'
    import React, { forwardRef } from 'react'
    
    interface Props extends React.ComponentPropsWithoutRef<'input'> {
      err?: boolean
      maxWidth?: string
    }
    
    const Input = forwardRef<HTMLInputElement, Props>((props, ref) => {
      return <StyledInput ref={ref} {...props} />
    })
    
    
    const StyledInput = styled.input<Props>`
      margin: 5px;
      background-color: ${({ theme, type }): string => (type === 'color' ? 'transparent' : theme.secondaryColor)};
      color: ${({ theme }): string => theme.textColor};
      max-width: calc(${({ maxWidth }): string => maxWidth || '100%'} - ${defPadding * 2}px);
      width: 100%;
      text-align: center;
    `
    
    Input.displayName = 'Input'
    
    export { Input }
    

    然后按照我的意愿使用它或覆盖它的默认样式

    import React from 'react'
    import styled from 'styled-components'
    import {Input} from '@frontend'
    
        export default function App() {
          return (
             <Input type="submit" value="Submit" err={true} />
             <RestyledRedInput type="submit" value="Submit" />
          )
        }
    
        // you can restyle it because of forward ref
        const RestyledRedInput = styled(Input)`
          background-color: red;
        `
    

    对于主题,我建议您使用上下文:

    import React, { useState, useEffect } from 'react'
    import { clone } from 'global'
    import { defaultGeneralTheme } from '../data/defaultGeneralTheme'
    import { ThemeProvider, createGlobalStyle } from 'styled-components'
    
    export const ThemeContext = React.createContext(null)
    export const ThemeContextProvider = props => {
      const [generalTheme, setGeneralTheme] = useState(clone(defaultGeneralTheme))
      const [theme, setTheme] = useState(currentTheme())
      const [isDay, setIsDay] = useState(isItDay())
    
      useEffect(() => {
        setTheme(currentTheme())
        setIsDay(isItDay())
      }, [generalTheme])
    
      function currentTheme() {
        return generalTheme.isDay ? generalTheme.day : generalTheme.night
      }
    
      function isItDay() {
        return generalTheme.isDay ? true : false
      }
    
      return (
        <ThemeContext.Provider value={{ theme, generalTheme, setGeneralTheme, isDay }}>
          <ThemeProvider theme={theme}>
            <>
              <GlobalStyle />
              {props.children}
            </>
          </ThemeProvider>
        </ThemeContext.Provider>
      )
    }
    
    const GlobalStyle = createGlobalStyle`
      /* Global */
      html {
        word-break: break-word;
      }
      body {  
        line-height: 1.2rem;
        background-color: ${({ theme }) => theme.secondaryColor};
      }
    `
    

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 2017-12-23
      • 2021-09-29
      • 2021-08-24
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多