【问题标题】:Cannot seem to style my component via boolean value似乎无法通过布尔值设置我的组件的样式
【发布时间】:2019-12-16 15:40:38
【问题描述】:

使用 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"));

【问题讨论】:

  • 请将模板贴在您实际使用样式 H1 的地方。
  • @IngoSteinke - 道歉。 JS 文件实际上称为 Title.js,在主模板中用作 &lt;Title&gt;
  • 那个doesMatch函数没有返回任何东西,所以显然它不会工作。
  • return name.includes(match); 怎么样?这不符合我的预期吗?
  • 不,它只在传递给forEach的每个回调的主体中返回,而不是在doesMatch中。

标签: javascript css reactjs styled-components


【解决方案1】:

在您的情况下,您应该将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);
  });
}

【讨论】:

  • 哦!我从来没有想过要在.find 上退货!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 2018-03-12
相关资源
最近更新 更多