【问题标题】:how to add background color only for actived item in a <li> using styled component?如何使用样式化组件仅为 <li> 中的活动项目添加背景颜色?
【发布时间】:2019-05-06 15:10:56
【问题描述】:

只是想知道如何使用样式组件为活动项目添加背景颜色?几乎像 jQuery 的添加/删除类一样工作。

我在我的状态下定义了一个活动布尔变量,如下所示:

constructor(props) {
    super(props);
    this.state = {
      placeholder: '',
      active: false,
    };
    this.handleClick = this.handleClick.bind(this);
    this.handleImageError = this.handleImageError.bind(this);
  }

handleClick 函数可以像这样将 true active 变为 true:

handleClick() {
    this.setState({ active: true });
  }

在我的渲染函数中,我有这样的 HTML:

 <MemberStyled className="member-item" active={active} onClick={this.handleClick}>
        <MemberStyled.avatar src={imgSource || placeholder} onError={this.handleImageError} />
        <MemberStyled.user>{name}</MemberStyled.user>
 </MemberStyled>

在 member.styles.js 文件中,我有这样的样式:

const MemberStyled = styled.li`
 background-color: ${props => props.active ? red : 'transparent'};
`;

现在,所有点击的项目都将颜色变为红色。如何在样式组件中仅使活动项目具有红色背景?

非常感谢!

【问题讨论】:

  • 非常感谢!它有效

标签: reactjs styled-components


【解决方案1】:

所以所有member-items 看起来都是更高父组件的一部分。您应该将活动状态推送到此父级。然后给每个 member-item 一个唯一的道具(索引或 id 应该这样做)。然后在调用父级的handleClick 时,向其发送唯一编号,父级应存储该编号而不是布尔值。最后,在 parent 的渲染中,将唯一 number 属性值与活动状态值进行比较,并将其作为 active 布尔值属性发送到 member-item。在member-item 的渲染中使用这个布尔值。

// in Parent Component
handleClick(activeKey){
   this.setState({activeKey});
}

isActive(key){
  const {activeKey} = this.state;
  return key === activeKey;
}

render(){
  return this.memberItems.map((index, itemData) => <MemberStyled active={this.isActive(index)} itemKey={index} handleClick={this.handleClick.bind(this, index)} />)
}

【讨论】:

  • 谢谢!有用。我用你的方式来比较目标项目 id 来实现这一点
【解决方案2】:

对我来说最好的方法是将活动元素的索引保存在父组件中:

  constructor(props) {
    super(props);
    this.state = {
      placeholder: '',
      active: -1,
    };
    this.handleClick = this.handleClick.bind(this);
    this.handleImageError = this.handleImageError.bind(this);
  }

  onClick(e, index) {
    this.setState({
      active: index,
    });
  }

  render() {
    const { active } = this.state;
    return this.memberItems.map((itemData, index) => <MemberStyled active={index === active} itemKey={index} handleClick={() => handleClick(this, index)} />)
}

【讨论】:

  • 非常感谢!这个想法很像上面的两个答案。他们都工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 2011-03-21
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
相关资源
最近更新 更多