ReactJS高阶组件在渲染循环中不转发属性

ReactJS high order components not forwarding property in a render loop

本文关键字:转发 属性 循环 高阶 组件 ReactJS      更新时间:2023-09-26

我正在寻找一些指导。我遵循React拖放象棋教程,将相同的原则应用到我的项目中。但是当子类需要递归重复时,我陷入了困境。当Child从Parent渲染时,一切都工作了。但是,当我递归地从一个子渲染函数呈现一个子,我得到关于丢失默认道具的错误,应该由DragSource()根据高阶组件的工作方式转发。我将在代码下面给出props的控制台输出。

在下面的代码中是我试图做的一个简化版本:

Constants.js

export const ItemTypes = {
  CHILD: 'child'
}

Parent.jsx

import React, { PropTypes } from 'react'
import Child from './Child'
import { DragDropContext } from 'react-dnd'
import HTML5Backend from 'react-dnd/modules/backends/HTML5'
class Parent extends React.Component {
  render () {
    return (
      <Child />
    ) 
  }
}
export default DragDropContext(HTML5Backend)(Parent)

Child.jsx

import React, { PropTypes } from 'react'
import { ItemTypes } from './Constants'
import { DragSource } from 'react-dnd'
const taskSource = {
  beginDrag (props) {
    return {
      index: props.index
    }
  }
}
function collect (connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging()
  }
}
class Child extends React.Component {
  static get propTypes () {
    return {
      index: PropTypes.number,
      connectDragSource: PropTypes.func.isRequired,
      isDragging: PropTypes.bool.isRequired
    }
  }
  constructor(props) {
    super(props)
    console.log(props)
    this.state = {
      children: [1, 2, 3, 4]
    }
  }
  render () {
      const { connectDragSource, isDragging } = this.props
      return connectDragSource(
          <ul className='children'>
            { this.state.children.map((child, i) =>
              <li key={child}>
                <Child index={i} ref={'child/' + i} />
              </li>
            ) }
          </ul>
      )
  }
}
export default DragSource(ItemTypes.CHILD, taskSource, collect)(Child)

从父组件渲染函数调用子组件道具时的Console.log输出

{
  _id: "123"",
  connectDragSource: fn(),
  isDragging: false
}

从子组件呈现函数递归调用子组件道具时的Console.log输出

{
  _id: "1234"
  index: 0
}
ERROR: Uncaught (in promise) TypeError: connectDragSource is not a function

所以基本上我认为发生的事情是高阶组件没有将默认道具转发给从子组件循环呈现的子组件。

我希望任何人都能给我一些建议,因为我已经研究了几个小时了。谢谢。

所以这实际上是我学到的一个非常简单的答案。Parent中导入的子节点。jsx与child .jsx中的子节点不同。parent中的Child类具有高阶组件的行为,而对其自身的子引用尚未应用高阶组件。为了解决这个问题,我必须在Child.jsx:

中这样做
render () {
  const { connectDragSource, isDragging } = this.props
  return connectDragSource(
      <ul className='children'>
        { this.state.children.map((child, i) =>
          <li key={child}>
            <HigherChild index={i} ref={'child/' + i} />
          </li>
        ) }
      </ul>
  )
}
const HigherChild = DragSource(ItemTypes.CHILD, taskSource, collect)(Child)
export default HigherChild