【发布时间】:2019-12-16 15:40:38
【问题描述】:
使用 Styled-components,我尝试根据自定义组件的内容设置其样式。但是我似乎无法完全正确。
我认为问题在于forEach 如何将布尔值带回来,而不是在正确的时间退出?我已经用控制台日志进行了调试,并且可以确认该函数确实看到了比较是否正确,只是当时没有更改css?
Title.js
import styled from "styled-components";
const toMatch = ["1", "2"];
function doesMatch(name) {
toMatch.forEach(match => {
return name.includes(match);
});
}
export default styled.h1`
background: ${props => (doesMatch(props.data) ? "blue" : "green")};
`;
模板
const x = [{ name: "1" }, { name: "2" }, { name: "3" }];
const App = () => (
<Wrapper>
{x.map(inf => (
<Title key={inf.name} data={inf.name}>
{inf.name}
</Title>
))}
</Wrapper>
);
render(<App />, document.getElementById("root"));
【问题讨论】:
-
请将模板贴在您实际使用样式 H1 的地方。
-
@IngoSteinke - 道歉。
JS文件实际上称为Title.js,在主模板中用作<Title>。 -
那个
doesMatch函数没有返回任何东西,所以显然它不会工作。 -
return name.includes(match);怎么样?这不符合我的预期吗? -
不,它只在传递给
forEach的每个回调的主体中返回,而不是在doesMatch中。
标签: javascript css reactjs styled-components