2017-08-24 51 views
0

嘗試將「s」字符串添加到在帶風格的組件中傳遞的道具時遇到問題。另外,我不完全確定我是否可以在樣式化組件中使用prop.x。這就是我的意思是:帶風格的組件中的字符串的Concat支持值

const MyComponent = (props) => { 
 
    const StyledLineItem = styled.li` 
 
    animation: ${someAnime}; 
 
    animation-delay: ${props.x}; // <- will this work? 
 
// here i need to add the 's' to the end 
 
// but i can't use `` becaouse of the fact that styled components 
 
// are in a template tag already... at least i think that's why 
 
// i get errors when i try `${props.x}s` 
 
// also, i haven't tested but will using ${prop.x} in a styled-component 
 
// like this even work? 
 
    ` 
 
    return (
 
    <StyledLineItem>{props.text}</StyledLineItem> 
 
) 
 
} 
 

 
// in my main component... 
 

 
// ... react component stuff 
 
    render() { 
 
    return (
 
     <ul> 
 
     {_.map(data, (item, i) => <MyComponent key={i} text={item.text})} 
 
     </ul> 
 
    ) 
 
    }

讓我知道,如果我能上的東西更清楚。

回答

1

變量可以正常工作後添加「s」。

`animation-delay: ${props.x}s`

代碼勝過千言萬語

var x = .3; 
 
var a = `animation-delay: ${x}s`; 
 
var b = "animation-delay: "+x+"s"; 
 
console.log(a===b) //true

+0

我想,第一,由於某種原因,沒有工作......但現在它呢!穆斯塔有一個更大的問題或類型o ...感謝Ekkasit! – archae0pteryx

1

是的,你可以使用``模板標籤內,是的,你可以使用道具來生成你的風格通過使用函數來插入值,在您的代碼中,例如:

const MyComponent = (props) => { 
    const StyledLineItem = styled.li` 
    animation: ${someAnime}; 
    animation-delay: ${props => `${props.x}s` : '0'}; 
    ` 
    return (
    <StyledLineItem>{props.text}</StyledLineItem> 
) 
} 

// in my main component... 

// ... react component stuff 
    render() { 
    return (
     <ul> 
     {_.map(data, (item, i) => <MyComponent key={i} text={item.text})} 
     </ul> 
    ) 
    } 

更多信息:

https://www.styled-components.com/docs/basics#adapting-based-on-props

+0

謝謝你的回答。我曾嘗試使用外部模板標籤內的模板標籤,但是我在蜜蜂后部發現了錯誤。然而,我並沒有使用匿名功能......也許這是問題所在。實際上,在傳遞給它之前我最終格式化了我的'''props.x'''。我會嘗試你的方法。 – archae0pteryx