簡體   English   中英

故事書:不使用反引號 after.attrs 時,對象作為 React 子項無效

[英]Storybook: Objects are not valid as a React child when not using backticks after .attrs

我有以下簡單styled-component

const Button = styled.bytton.attrs(({primary}) => ({
  className: primary ? 'something' : 'something-else'
})

現在由於某種原因,除非我 append ed 中的反引號,例如:

const Button = styled.bytton.attrs(({primary}) => ({
  className: primary ? 'something' : 'something-else'
})`` // here

我會從故事書中得到一個錯誤:

對象作為 React 子對象無效(發現:object 帶有鍵 {$$typeof, render, attrs, >componentStyle, displayName, foldedComponentIds, styledComponentId, target, withComponent, >warnTooManyClasses, toString})。 如果您打算渲染一組子元素,請使用數組 > 而不是。

理想情況下,我想避免在代碼庫中放置隨機反引號只是為了抑制錯誤......

如果您正在使用樣式化組件 api 來創建共享邏輯的通用組件,那么您可能只想創建一個更高階的組件。

function withProps(Component, propSetter) {
  return (props) => {
    const additionalProps = propSetter(props)
    return <Component {...props} {...additionalProps} />
  }
}

const Button = withProps('button', ({ primary }) => ({
  className: primary ? 'something' : 'something-else'
})

但是要給出原始問題的上下文:

提到的反引號並不像看起來那么隨機。 當您看到它們空無一物時,它們可能會感到奇怪,但它們確實是有目的的。 要了解它們的用途,可能更容易查看當反引號或標記的模板文字編譯成常規 JavaScript 時實際發生的情況。

// Before
styled.button`
  color: green;
`

// After
styled.button(['color: green;'])

如您所見,字符串被傳遞到從 styled.button 返回的 function 中,styled.attrs 返回相同的 function。 現在上面的例子並沒有充分利用反引號的力量。 真正的力量來自 function 調用。

// Before
styled.button`
  color: ${props => props.theme.color};
`

// After
styled.button(['color: ', ';'], props => props.theme.color)

如您所見,它已將模板與輸入分開。 function 的第一個參數是模板,下面的 arguments 是數組中每個部分之后 go 的輸入。 這就是樣式化組件如何傳遞你的道具來在你的組件中做一些特殊的事情。

styled.buttonstyled.button.attrs()都返回一個 function 以這種方式使用標記的模板文字調用。 如果他們返回一個可渲染的 React 組件,那么您將根本無法提供 css。

當您嘗試在沒有反引號的情況下呈現某些內容時,您在 Button 中的值是 object,其中包含准備好創建組件的信息。 在您通過()或 `` 調用 object 之前,您將沒有可以渲染的組件。

如果反引號太奇怪了,那么用()替換它們可能會更舒服? 或者,您可以考慮創建一個包裝器 function 或其他東西以確保它們總是被調用。

.attrs用於重構組件的道具(使用默認值或某些操作)以用於正常樣式。

const Button = styled.button.attrs(props => ({
  layoutSize: props.size || '1em',
}))`
  margin: ${props => props.layoutSize};
  padding: ${props => props.layoutSize};
  ...
`

參考:何時使用 attrs的文檔


如果我們只想將 props 用於樣式,我們可以在沒有.attrs的情況下使用它

const Button = styled.button`
  margin: ${props => props.marginSize || '1em'};
  padding: ${props => props.paddingSize || '2em'};
  ...
`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM