gpt4 book ai didi

javascript - 如何在 React 中创建可排序的表格?如何从排序的对象访问类方法?

转载 作者:行者123 更新时间:2023-11-30 06:17:57 28 4
gpt4 key购买 nike

我有一个对象数组。我想访问对象函数属性中的类方法。如何实现?请帮我。我是这样写的:

render() {       
tableTh = [
{name: i18n.t('ExtendedModalBar.naming'), style:{}, handleSort () {}},
...
]
...
}

我想写这样的东西:

class Table extends Component {

handleSort() {

}
...

render() {
}

}

我的表格标题是动态形成的:

<thead>
<tr>
<th style={{ width: "50px" }}>
<Checkbox
checked={this.state.selectedAll}
onChange={() => this.selectAll()}
/>
</th>
{tableTh.map((obj, index) => {
return (
<th key={index.toString()} style={obj.style} onClick={obj.handleSort}>
{obj.name}
</th>
);
})}
</tr>
</thead>

我必须实现表格列的排序。如果表格是静态形成的,则很容易将 onclick 附加到标签上。但如果代码是这样写的,我就卡住了。如何在类中编写可从对象(对象数组)的内部属性访问的方法?我需要在升序和降序两个方向上进行排序。当我点击它的表头时,我的表列应该改变自己的排序方向。任何答案都将被考虑在内。提前致谢

最佳答案

在状态本身上具有状态更改功能的问题在于,这本身就很难操纵状态。

var data = [
{ name: 'a', change: /* ??? */ },
{ name: 'b', change: /* ??? */ },
{ name: 'c', change: /* ??? */ }
]

// How do we write the function ??? to change the order of data?

将数据操作逻辑提升到更高级别(在数据本身之外)要简单得多。

在这种情况下,我们会将数据操作逻辑放在类本身而不是每个项目中。

我们可以利用 state 来做到这一点在 React 中。

状态用于保存组件的任何(动态)展示(渲染)数据。动态(变化的)表示数据的一个示例是对其列进行排序的表格。

我们想要将展示数据放入状态的原因是 React 允许我们重新触发展示(通过重新渲染)以始终显示我们数据的最新值。

我们可以通过更改数据本身而不是任何表示逻辑来实现这一点。这就是为什么 React 组件结构被称为 declarative 的原因.

每当状态更新时,React 都会调用 render 函数来获取具有最新状态更改的组件结构,并将其显示在适当的媒体上(在您的情况下为 DOM )

这是合并状态以创建可排序表的一种方法:

class Table extends React.Component {
constructor(props) {
super(props);

this.state = {
sortDirection: "asc", // we start with ascending order by default
selectedHeaderIndex: 0 // we start by sorting based on the first header (the one in position 0)
};

this.ascComparator = (row1, row2) =>
row1[this.state.selectedHeaderIndex].localeCompare(
row2[this.state.selectedHeaderIndex]
);

this.descComparator = (row1, row2) =>
row2[this.state.selectedHeaderIndex].localeCompare(
row1[this.state.selectedHeaderIndex]
);

this.flipSortDirection = () =>
this.state.sortDirection === "asc" ? "desc" : "asc";
}

render() {
const { headers, rows } = this.props.table;

const comparator =
this.state.sortDirection === "asc"
? this.ascComparator
: this.descComparator;

// sort the rows based on the selected header
const sortedRows = rows.sort(comparator);

return (
<table>
<thead>
{headers.map((header, i) => (
<th
onClick={() => {
this.setState({
// if we clicked on the already selected index, we flip the sort direction
sortDirection:
this.state.selectedHeaderIndex === i
? this.flipSortDirection()
: "asc",
selectedHeaderIndex: i
});
}}
>
{header}
</th>
))}
</thead>
<tbody>
{sortedRows.map(row => (
<tr>
{row.map(cell => (
<td>{cell}</td>
))}
</tr>
))}
</tbody>
</table>
);
}
}

const table = {
headers: ["h1", "h2", "h3"],
rows: [["a", "9", "+"], ["b", "6", "-"], ["c", "3", "="]]
};

ReactDOM.render(<Table table={table} />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

使用 hooks代码变得更具可读性(click for the CodeSandbox example 因为 SO 还不支持 React 16.8):

function Table({ table }) {
const { headers, rows } = table;

const [selectedHeaderIndex, setSelectedHeaderIndex] = React.useState(0); // we start by sorting based on the first header (the one in position 0)
const [sortDirection, setSortDirection] = React.useState("asc"); // we start with ascending order by default

// determine the sorting comparator based on the sorting direction
const comparator =
sortDirection === "asc"
? (row1, row2) =>
row1[selectedHeaderIndex].localeCompare(row2[selectedHeaderIndex])
: (row1, row2) =>
row2[selectedHeaderIndex].localeCompare(row1[selectedHeaderIndex]);

const flipSortDirection = () => (sortDirection === "asc" ? "desc" : "asc");

// sort the rows based on the selected header
const sortedRows = rows.sort(comparator);

return (
<table>
<thead>
{headers.map((header, i) => (
<th
onClick={() => {
setSelectedHeaderIndex(i);
setSortDirection(
selectedHeaderIndex === i ? flipSortDirection() : "asc"
);
}}
>
{header}
</th>
))}
</thead>
<tbody>
{sortedRows.map(row => (
<tr>
{row.map(cell => (
<td>{cell}</td>
))}
</tr>
))}
</tbody>
</table>
);
}

const table = {
headers: ["h1", "h2", "h3"],
rows: [["a", "9", "+"], ["b", "6", "-"], ["c", "3", "="]]
};

ReactDOM.render(<Table table={table} />, document.querySelector("#root"));

关于javascript - 如何在 React 中创建可排序的表格?如何从排序的对象访问类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015470/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com