我目前正在使用
将两个回调传递给子组件 React.cloneElement
在检查我的项目时,我注意到activeRow
始终存在但deactivateRow
为undefined
。
你可以告诉我一个可能导致这个问题的原因吗?
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>
)
}
}
答案 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>
)
}
}