[英]React custom Component(DataTable)
我是新手,我正在尝试使用参数构建自定义组件。
我只是想知道这样做的确切方法是什么。
这是我当前的代码,我应该如何将这些Columns
、 ajax
和datasource
传递给组件。 还是我做错了?
import * as React from 'react';
interface Column {
name: string,
header: string,
value: Function
}
export default class DataTable extends React.PureComponent<({
dataSource: any[],
ajax: string
columns: Column[]
onEdit: Function,
onDelete: Function
})>{
public state = {
dataSource: [],
ajax: undefined,
columns: [],
onEdit: undefined,
onDelete: undefined
}
componentDidMount() {
if (this.state.ajax != undefined) {
fetch(this.state.ajax)
.then(response => response.json())
.then(data => this.setState({ dataSource: data }));
}
}
render() {
var template = (
<table className="table">
<thead className="thead-darked">
{
this.state.columns.map((x: Column) => {
<th scope="col">{x.header}</th>
})
}
</thead>
</table>)
return template;
}
}
ajax
、 columns
、 onEdit
和onDelete
state。 只需使用道具。this.props.dataSource
this.state.dataSource
上面的两个更改将解决您的问题。 此外,
ajax
发生变化,您可能需要再次获取数据。 您必须为该行为实现componentDidUpdate
方法。 但是,我建议制作一个 function 组件并使用useEffect
挂钩。dataSource
属性更改,您的dataSource
state 将不会更新。 尽管您可以添加更多代码来避免错误,但它可能会导致错误行为。 如果将“ajax”部分移到组件之外并且只使用dataSource
属性,那么逻辑会更清晰且不易出错。以下是更新后的代码。
interface Props {
dataSource: any[],
ajax: string,
columns: Column[],
onEdit: Function,
onDelete: Function
}
export default class DataTable extends React.PureComponent<Props>{
public state = {
dataSource: this.props.dataSource,
}
componentDidMount() {
if (this.props.ajax != undefined) {
fetch(this.props.ajax)
.then(response => response.json())
.then(data => this.setState({ dataSource: data }));
}
}
render() {
const template = (
<table className="table">
<thead className="thead-darked">
{
this.props.columns.map((x: Column) => {
<th scope="col">{x.header}</th>
})
}
</thead>
{/* render something with this.state.dataSource */}
</table>
);
return template;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.