简体   繁体   English

className 的动态样式在反应中不起作用

[英]Dynamic styling of className not working in react

I am trying to code along to a tutorial video but the dynamic styling of className isn't working.我正在尝试编写教程视频,但 className 的动态样式不起作用。 Though it seems to work on regular CSS, I'm using styled-components instead but I don't get the same outcome.虽然它似乎适用于常规 CSS,但我使用的是样式化组件,但我没有得到相同的结果。 The end result is supposed to be a differently styled "type" according to its value.根据其值,最终结果应该是不同样式的“类型”。 Please help请帮忙

// import ContactContext from '../../context/contact/contactContext';

const ContactItemStyles = styled.div`
  .class-bg-light {
    color: grey;
  }
  .badge {
    font-size: 0.8rem;
    padding: 0.2rem 0.7rem;
    text-align: center;
    margin: 0.3rem;
    background: var(--green);
    color: #333;
    border-radius: 5px;
  }
  .badge-success {
    background: var(--green);
    color: #fff;
  }
  .badge-primary {
    background: red;
  }
`;
const ContactItem = ({ contact }) => {
  const { _id, name, email, phone, type } = contact;
  return (
    <ContactItemStyles>
      <div className='class-bg-light'>
        <h3 className='text-primary text left'>
          {name} {''} 
          <span
            className={
              'badge' +
              (type === 'professional' ? 'badge-success' : 'badge-primary')
            }
          >
            {type}
          </span>
        </h3>
      </div>
    </ContactItemStyles>
  );
};

ContactItem.propTypes = {
  contact: PropTypes.object.isRequired,
};

export default ContactItem;```

Add space after class badge so, they dont combined together without space.在 class 徽章之后添加空格,这样它们就不会在没有空格的情况下组合在一起。

className={
     'badge ' +
     (type === 'professional' ? 'badge-success' : 'badge-primary')
    }

Almost there.差不多好了。 Your mistake was concatenating the string values together inside className, Let's say in your example that type is 'professional': what you would end up with looks like this:您的错误是在 className 中将字符串值连接在一起,假设在您的示例中类型是“专业”:您最终会得到的结果如下所示:

className={'badge' + 'badge-success'} 
// This becomes 'badgebadge-success' 

You could add a space after your first class, or alternatively I would recommend using string interpolation via backticks: `您可以在第一个 class 之后添加一个空格,或者我建议通过反引号使用字符串插值:`

So your code should look like this:所以你的代码应该是这样的:

className={`badge ${type === 'professional' ? 'badge-success' : 'badge-primary'}`}

Having the curly braces show where the strings are likely to end and start makes it clearer in case you missed any whitespace.使用花括号显示字符串可能结束和开始的位置可以让您更清楚地了解您错过任何空格的情况。

Keep up the learning and good luck!继续学习,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM