我正在寻找一些指导。我已经关注了React Drag-n-Drop chess tutorial将相同的原则应用于我的项目。但是当子类需要递归重复时我陷入了困境。当从父级渲染子级时,一切正常。但是,当我从 Child 渲染函数递归渲染 Child 时,我收到了有关缺少默认 Prop 的错误,这些 Prop 应该根据高阶组件的工作方式由 DragSource( ) 转发。我将在代码下方给出 Prop 的控制台输出。
下面的代码是我想要做的事情的简化版本:
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)
从父组件渲染函数调用时子组件 Prop 的 Console.log 输出
{
_id: "123"",
connectDragSource: fn(),
isDragging: false
}
从子组件渲染函数递归调用时子组件 props 的 Console.log 输出
{
_id: "1234"
index: 0
}
ERROR: Uncaught (in promise) TypeError: connectDragSource is not a function
所以基本上我认为正在发生的事情是高阶组件没有将默认 Prop 转发到从子组件循环渲染的子组件。
我希望得到任何人的建议,因为我已经对此进行了几个小时的研究。谢谢。
最佳答案
所以这实际上是我学到的一个非常简单的答案。 Parent.jsx 中导入的子项与 Child.jsx 中导入的子项不同。父级中的子类具有高阶组件的行为,而子级对自身的引用尚未应用高阶组件。为了解决这个问题,我必须在 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
关于javascript - ReactJS 高阶组件不在渲染循环中转发属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791500/