我是 React 的新手,我正在尝试构建带有参数的自定义组件。
我只是想知道这样做的确切方法是什么。
这是我当前的代码,我应该如何将那些 Columns
、ajax
和 datasource
传递给 componenet。
还是我做错了?
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
状态。只需使用 Prop 。 - 用
this.props.dataSource
初始化this.state.dataSource
。
以上两项更改将解决您的问题。此外,
- 如果
ajax
属性发生变化,您可能需要再次获取数据。您必须为该行为实现componentDidUpdate
方法。但是,我建议制作一个函数组件并使用useEffect
Hook 。 - 如果
dataSource
属性发生变化,您的dataSource
状态将不会更新。尽管您可以添加更多代码来避免错误,但它可能会导致错误行为。如果将“ajax”部分移到组件之外,只使用dataSource
prop,逻辑会更清晰,更不容易出错。
下面是更新后的代码。
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;
}
}
关于javascript - react 自定义组件(数据表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891533/