如何将两个回调传递给React.cloneElement

时间:2018-03-07 15:57:32

标签: javascript reactjs

我目前正在使用

将两个回调传递给子组件

React.cloneElement

在检查我的项目时,我注意到activeRow始终存在但deactivateRowundefined

你可以告诉我一个可能导致这个问题的原因吗?

export class Row extends React.Component<Props, State> {
  state: State = {
    isActive: false,
  }
  activeRow = () => {
    this.setState({ isActive: true })
  }

  deactivateRow = () => {
    this.setState({ isActive: false })
  }

  render(): JSX.Element {
    const { classes, children } = this.props
    const { isActive } = this.state
    return (
      <TableRow className={isActive ? classes.active: classes.noActive}>
        {React.cloneElement(this.props.children, {
          activeRow: this.activeRow,
          deactivateRow: this.deactivateRow,
        })}
      </TableRow>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

React.cloneElement,只是克隆一个single React element,为了克隆更多的一个子元素,你需要映射所有的孩子并克隆它们

export class Row extends React.Component<Props, State> {
  state: State = {
    isActive: false,
  }
  activeRow = () => {
    this.setState({ isActive: true })
  }

  deactivateRow = () => {
    this.setState({ isActive: false })
  }

  render(): JSX.Element {
    const { classes, children } = this.props
    const { isActive } = this.state
    return (
      <TableRow className={isActive ? classes.active: classes.noActive}>
        {React.Children.map(this.props.children, (child) => {
           return React.cloneElement(child, {
                  activeRow: this.activeRow,
                  deactivateRow: this.deactivateRow
              }
          }
       )}
      </TableRow>
    )
  }
}