stopPropagation 在组件层次结构中不起作用



>我试图避免在每个特定行上出现onClick事件,每当单击一列数据下的 show/less 时。我有一个基本上具有选择和多选功能的网格。此外,其中一列显示更多/显示更少。每当我单击Show More/Less时,都会触发行选择。我想避免这种情况。有人能说出这里出了什么问题。比如说,如果有多个类似网格的实例,我希望该网格具有行选择功能,其中包含 prop

沙盒:https://codesandbox.io/s/react-table-row-table-alternate-single-row-working-5fr81

import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";
export default class DataGrid extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedRows: []
};
}
rowClick = (state, rowInfo) => {
if (rowInfo) {
let selectedRows = new Set();
return {
onClick: e => {
e.stopPropagation();
if (e.ctrlKey) {
selectedRows = this.state.selectedRows;
rowInfo._index = rowInfo.index;
if (
selectedRows.filter(row => row._index === rowInfo._index)
.length === 0
)
selectedRows.push(rowInfo);
else
selectedRows = selectedRows.filter(
row => row._index !== rowInfo._index
);
this.setState({
selectedRows
});
} else {
selectedRows = [];
rowInfo._index = rowInfo.index;
selectedRows.push(rowInfo);
}
this.setState(
{
selectedRows
},
() => {
console.log("final values", this.state.selectedRows);
this.props.rowClicked(this.state.selectedRows);
}
);
},
style: {
background:
this.state.selectedRows.some(e => e._index === rowInfo.index) &&
"#9bdfff"
}
};
} else {
return "";
}
};
render() {
return (
<ReactTable
data={this.props.data}
columns={this.props.columns}
getTrProps={this.rowClick}
/>
);
}
}

在 ShowMore 组件上,可以修改onClick事件处理程序以调用event.stopPropagation()。这将停止当前事件在捕获和冒泡阶段的进一步传播,并允许您单击显示更多/更少而不触发行选择。

const toggleTruncate = (e) => {
e.stopPropagation();
setShowMore(!isShowMore);
}

React 实际上定义了合成事件,它将在您的点击事件处理程序中可用,而无需调用document.addEventListener()。你可以在这里阅读更多关于 React 中的事件处理的信息。

回答问题的第二部分,鉴于rowClicked事件是DataGrid组件的可选 props,您需要在DataGrid组件上手动检查它,以确保只有在定义时才调用它。这是可以做到的:

if (rowClicked) {
// do the rest
}

这就是您的rowClick方法应该是什么样子的。请注意,我已经解构了第二行的 props 对象。这将确保仅在定义了rowClicked时才执行行选择逻辑。

rowClick = (state, rowInfo) => {
const { rowClicked } = this.props;
if (rowInfo && rowClicked) {
let selectedRows = new Set();
return {
onClick: e => {
e.stopPropagation();
if (e.ctrlKey) {
selectedRows = this.state.selectedRows;
rowInfo._index = rowInfo.index;
if (
selectedRows.filter(row => row._index === rowInfo._index)
.length === 0
)
selectedRows.push(rowInfo);
else
selectedRows = selectedRows.filter(
row => row._index !== rowInfo._index
);
this.setState({
selectedRows
});
} else {
selectedRows = [];
rowInfo._index = rowInfo.index;
selectedRows.push(rowInfo);
}
this.setState(
{
selectedRows
},
() => {
rowClicked(this.state.selectedRows);                
}
);
},
style: {
background:
this.state.selectedRows.some(e => e._index === rowInfo.index) &&
"#9bdfff"
}
};
} else {
return "";
}
};

最新更新