使用样式组件时如何保留原始 html 元素的道具?
How to preserve props of original html element when using styled components?
我发现自己处于当前情况,我有 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;
这里的问题发生在道具上,在某些组件中,我可能有额外的道具或覆盖上面的默认道具,但仍然想传递它们所有有效的 <input />
元素道具。我尝试了 2 种输入方法,即
props: React.ComponentProps<typeof InputPrint>
如果我这样做 ^ 当我使用 <Input />
时,道具上没有任何自动完成功能
props: React.HTMLProps<HTMLInputElement>
如果我这样做 ^ 我在 Input.tsx
中为 <StyledInput />
得到一个打字稿错误
const StyledInput: StyledComponent<"input", any, {}, never> Styles
No overload matches this call. Overload 1 of 2, '(props:
Pick,
HTMLInputElement>, "form" | ... 283 more ... | "step"> & { ...; },
"ref" | ... 284 more ... | "step"> & Partial<...>, "ref" | ... 284
more ... | "step"> & { ...; } & { ...; }): ReactElement<...>', gave
the following error.
Type '{ accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean |
undefined; allowTransparency?: boolean | undefined; alt?: string |
undefined; ... 353 more ...; key?: string | ... 1 more ... |
undefined; }' is not assignable to type
'Pick,
HTMLInputElement>, "form" | ... 283 more ... | "step"> & { ...; },
"ref" | ... 284 more ... | "step"> & Partial<...>, "ref" | ... 284
more ... | "step">'.
Types of property 'ref' are incompatible.
Type 'string | ((instance: HTMLInputElement | null) => void) | RefObject | null | undefined' is not assignable to
type '((instance: HTMLInputElement | null) => void) |
RefObject | null | undefined'.
Type 'string' is not assignable to type '((instance: HTMLInputElement | null) => void) | RefObject | null
| undefined'. Overload 2 of 2, '(props:
StyledComponentPropsWithAs<"symbol" | "object" | ComponentClass | FunctionComponent | "a" | "abbr" | "address" | "area" |
"article" | "aside" | "audio" | ... 164 more ... | "view", any, {},
never>): ReactElement<...>', gave the following error.
Type '{ accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean |
undefined; allowTransparency?: boolean | undefined; alt?: string |
undefined; ... 353 more ...; key?: string | ... 1 more ... |
undefined; }' is not assignable to type '(IntrinsicAttributes &
Pick & Partial>,
string | number | symbol> & { ...; } & { ...; }) |
(IntrinsicAttributes & ... 3 more ... & { ...; })'.
Type '{ accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean |
undefined; allowTransparency?: boolean | undefined; alt?: string |
undefined; ... 353 more ...; key?: string | ... 1 more ... |
undefined; }' is not assignable to type '{ as?: "symbol" | "object" |
ComponentClass | FunctionComponent | "a" | "abbr" |
"address" | "area" | "article" | "aside" | "audio" | ... 165 more ...
| undefined; }'.
Types of property 'as' are incompatible.
Type 'string | undefined' is not assignable to type '"symbol" | "object" | ComponentClass |
FunctionComponent | "a" | "abbr" | "address" | "area" | "article"
| "aside" | "audio" | ... 165 more ... | undefined'.
Type 'string' is not assignable to type '"symbol" | "object" | ComponentClass | FunctionComponent | "a" |
"abbr" | "address" | "area" | "article" | "aside" | "audio" | ... 165
more ... | undefined'.ts(2769)
我像这样导出默认样式的组件:
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};
}
`
问题有点老了。但它可能会帮助面临同样问题的其他人。如果您使用的是 Styled 组件,那么在这种情况下使用 transient 道具可能会有所帮助。
If you want to prevent props meant to be consumed by styled-components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.
const Comp = styled.div`
color: ${props =>
props.$draggable || 'black'};
`;
render(
<Comp $draggable="red" draggable="true">
Drag me!
</Comp>
);
我发现自己处于当前情况,我有 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;
这里的问题发生在道具上,在某些组件中,我可能有额外的道具或覆盖上面的默认道具,但仍然想传递它们所有有效的 <input />
元素道具。我尝试了 2 种输入方法,即
props: React.ComponentProps<typeof InputPrint>
如果我这样做 ^ 当我使用 <Input />
props: React.HTMLProps<HTMLInputElement>
如果我这样做 ^ 我在 Input.tsx
中为 <StyledInput />
const StyledInput: StyledComponent<"input", any, {}, never> Styles
No overload matches this call. Overload 1 of 2, '(props: Pick, HTMLInputElement>, "form" | ... 283 more ... | "step"> & { ...; }, "ref" | ... 284 more ... | "step"> & Partial<...>, "ref" | ... 284 more ... | "step"> & { ...; } & { ...; }): ReactElement<...>', gave the following error. Type '{ accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean | undefined; allowTransparency?: boolean | undefined; alt?: string | undefined; ... 353 more ...; key?: string | ... 1 more ... | undefined; }' is not assignable to type 'Pick, HTMLInputElement>, "form" | ... 283 more ... | "step"> & { ...; }, "ref" | ... 284 more ... | "step"> & Partial<...>, "ref" | ... 284 more ... | "step">'. Types of property 'ref' are incompatible. Type 'string | ((instance: HTMLInputElement | null) => void) | RefObject | null | undefined' is not assignable to type '((instance: HTMLInputElement | null) => void) | RefObject | null | undefined'. Type 'string' is not assignable to type '((instance: HTMLInputElement | null) => void) | RefObject | null | undefined'. Overload 2 of 2, '(props: StyledComponentPropsWithAs<"symbol" | "object" | ComponentClass | FunctionComponent | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | ... 164 more ... | "view", any, {}, never>): ReactElement<...>', gave the following error. Type '{ accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean | undefined; allowTransparency?: boolean | undefined; alt?: string | undefined; ... 353 more ...; key?: string | ... 1 more ... | undefined; }' is not assignable to type '(IntrinsicAttributes & Pick & Partial>, string | number | symbol> & { ...; } & { ...; }) | (IntrinsicAttributes & ... 3 more ... & { ...; })'. Type '{ accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean | undefined; allowTransparency?: boolean | undefined; alt?: string | undefined; ... 353 more ...; key?: string | ... 1 more ... | undefined; }' is not assignable to type '{ as?: "symbol" | "object" | ComponentClass | FunctionComponent | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | ... 165 more ... | undefined; }'. Types of property 'as' are incompatible. Type 'string | undefined' is not assignable to type '"symbol" | "object" | ComponentClass | FunctionComponent | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | ... 165 more ... | undefined'. Type 'string' is not assignable to type '"symbol" | "object" | ComponentClass | FunctionComponent | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | ... 165 more ... | undefined'.ts(2769)
我像这样导出默认样式的组件:
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};
}
`
问题有点老了。但它可能会帮助面临同样问题的其他人。如果您使用的是 Styled 组件,那么在这种情况下使用 transient 道具可能会有所帮助。
If you want to prevent props meant to be consumed by styled-components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.
const Comp = styled.div`
color: ${props =>
props.$draggable || 'black'};
`;
render(
<Comp $draggable="red" draggable="true">
Drag me!
</Comp>
);