javascript - 有条件地将函数作为 props 传递给组件

标签 javascript html css reactjs

我有这个面包屑组件,它映射 Prop 并呈现如下芯片组件列表:

class BreadCrumb extends React.Component {
    render () {
      const {
        steps,
        activeIndex
      } = this.props;

      const chips = steps
        .map((step,index) => {

          return <Chip 
                  key={index} 
                  title={step.category} 
                  onClick = {()=> this.props.selectChip(index)}   // this should be passed only if 
                                                                  //                active == true
                  active={activeIndex >= index} />
              })

      return (
        <div className="chip-container">
            {chips}
        </div>
      )
    }
  }

只有当他的事件 Prop 为真时,我才需要点击筹码, 这是芯片组件

class Chip extends React.Component {
    render(){
      const {
        active,
        title
      } = this.props;

      const activeClassName = active ? 'chip active' : 'chip';

      return (
        <div 
            className = {activeClassName}
            onClick = {() => this.props.onClick()} >  
              <span>{title}</span>
        </div>
      )

    }
  }

只有在 active 属性为 true 的情况下,我才能使芯片可点击?

更多信息 selectChip() 函数设置组件 App 的状态,Breadcrump 组件的父级,因此它被绑定(bind)到 App 组件。

最佳答案

你可以例如将 onClick 设为类方法并在内部使用简单条件:

class Chip extends React.Component {
    handleClick = () => {
       if (this.props.active) {
          this.props.onClick(); // call only if active props is true
       }
    }

    render() {
      const { active, title } = this.props;

      const activeClassName = active ? 'chip active' : 'chip';

      return (
        <div 
            className = {activeClassName}
            onClick = {this.handleClick}
        >  
            <span>{title}</span>
        </div>
      )

    }
 }

关于javascript - 有条件地将函数作为 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212799/

相关文章:

javascript - jQuery 在 ajax 调用后,具有相同 Id 的事件停止工作

javascript - Nodejs REST Api 的 Keycloak 策略执行

javascript - 麻烦 - Node js 将文件从文件夹 x 移动到文件夹 y

HTML5 嵌套可点击元素

javascript - 判断父容器子元素是否包含特定类并执行某些操作的条件

css - 如何删除 CSS 三 Angular 形?

html - 圆圈在事件时不会改变颜色

html - 如何更改药丸的 CSS? ( Angular 2)

javascript - 使用 jquery for mobile 删除一个 div

javascript - 如何使用正则表达式检查所有 html 标签是否已关闭