【问题标题】:How to add an active CSS property to a React component?如何将活动 CSS 属性添加到 React 组件?
【发布时间】:2016-10-06 03:12:12
【问题描述】:

我正在尝试添加一些样式,以便当我单击一个项目时它具有不同的背景颜色。

我有一个类 App,它导入类 ItemSection,它导入类 ItemList。在 ItemSection 和 ItemList 中,我的 propTypes 中都声明了 activeItem: React.PropTypes.object.isRequired

我认为问题出在我的 App 的渲染方法上:

  render(){
return(
  <div className = 'app'>
    <div className = 'manipulateItem'> {/*Need a better className*/}
      <ItemSection
        items = {this.state.items}
        addItem = {this.addItem.bind(this)}
        setItem = {this.setItem.bind(this)}
        deleteItem = {this.deleteItem.bind(this)}
        editItem = {this.editItem.bind(this)}
        activeItem = {this.state.activeItem} /*THIS LINE I BELIEVE*/
      />
    </div>
  </div>
)
}

这是我的回溯:

bundle.js:1251 警告:失败的道具类型:必需的道具activeItem 未在ItemList 中指定。 在 ItemList 中(由 ItemSection 创建) 在 ItemSection 中(由 App 创建) 在 div 中(由 App 创建) 在 div 中(由 App 创建) 应用内

【问题讨论】:

  • 这是来自ItemList,请您发布所有三个组件的代码。此外,您的问题最初是关于背景颜色,然后切换到 propType 警告。只是想了解您主要关心的是什么。

标签: css reactjs


【解决方案1】:

您在问题中声明您在 propTypes 中声明了 activeItem: React.PropTypes.object.isRequired,但您特别要求在状态对象中使用 activeItem - activeItem = {this.state.activeItem}。如果要在传递给组件的 props 中使用 activeItem 的值,则必须使用 this.props.activeItem

希望这会有所帮助!

【讨论】:

  • 好吧,我改变了这个,现在我得到另一个错误:bundle.js:1251 警告:失败的道具类型:必需的道具activeItem 未在ItemList 中指定。在 ItemList 中(由 ItemSection 创建) 在 ItemSection 中(由 App 创建) 在 div 中(由 App 创建) 在 div 中(由 App 创建) 在 App 中奇怪的是我在 ItemList.jsx 中也有 activeItem = {this.props.activeItem}
  • 如果我理解正确,你有 app.js,它是一个具有渲染函数的组件,它正在渲染 ItemSection,而你在 ItemSection 上你想应用一个名为 @987654328 的属性@ 并将来自应用程序默认道具的 this.props.activeItem 的值传递给该属性。因此,如果您遇到像 error: bundle.js:1251 Warning: Failed prop type: Required prop activeItem was not specified in ItemList. 这样的错误,则意味着您传递给 ItemSectionactiveItem 属性可能是未定义的。
  • App.jsx 正在创建 ItemSection,它会创建 ItemList,对吗?因此,如果您需要使用this.props.activeItem 设置类名或其他内容,只需添加类似className={this.props.activeItem ? 'active-item' : ' '}
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2016-12-16
  • 2020-01-27
  • 2021-01-12
  • 2015-07-12
相关资源
最近更新 更多