似乎无法通过布尔值设置我的组件的样式

Cannot seem to style my component via boolean value

使用 Styled-components,我试图根据它们的内容来设置自定义组件的样式。但是我似乎不太正确。

Here is a sandbox

我认为问题在于 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"));

您应该将 return 值添加到 doesMatch,在您的情况下:

function doesMatch(name) {
//  v Return a boolean from `doesMatch` function
  return toMatch.find(match => {
//                ^ Change from `forEach` which is void function.
    return name.includes(match);
  });
}