首页 > 解决方案 > 如何将自定义属性传递给功能组件中的样式组件?

问题描述

我试图了解这件事是如何工作的,但我发现的所有示例都是以课堂方式编写的。

   import React from 'react'
   import styled from 'styled-components/native'

   const MyTag = styled.Button.attrs({
     title: myThisThingValue
   })`
     // some style
     background: thisIsAlsoMyThingValue
   \` 

   export default function MyComponent({ props }) {
     return(
       <MyTag myThisThing="My value" thisIsAlsoMyThing="Other Value" />
         )
   }

我只想访问 MyTag 样式中的自定义属性。我(props) => {title: props.MyThing }在 .attrs() 中使用了一个但没有用。

标签: javascriptreactjsreact-nativereact-native-androidstyled-components

解决方案


这应该工作:

JavaScript 版本:

export const MyTag = styled.button.attrs(props => ({
  title: props.myThisThingValue,
}))`
  background: ${props => props.thisIsAlsoMyThing};
`;

打字稿版本:

interface MyTagProps {
  myThisThingValue: string;
  thisIsAlsoMyThing: string;
}

export const MyTag = styled.button.attrs((props: MyTagProps) => ({
  title: props.myThisThingValue,
}))<MyTagProps>`
  background: ${props => props.thisIsAlsoMyThing};
`;

用它:

<MyTag myThisThingValue="My value" thisIsAlsoMyThing="red" />

推荐阅读