我正在使用react-table,并且希望基于从父元素传递过来的道具来渲染带有/不带有subComponent的表。
我尝试更新状态-使用data
和columns
的新数组,但是表没有重新呈现。
js
import React from "react";
import { render } from "react-dom";
import { makeData, Logo, Tips } from "./Utils";
// Import React Table
import ReactTable from "react-table";
import "react-table/react-table.css";
const data = [
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
},
{
a: "32,000.02938488",
b: "0",
c: "32,000.02938488",
d: "55,000"
}
];
const columns = [
{
Header: "a",
accessor: "a"
},
{
Header: "b",
accessor: "b"
},
{
Header: "c",
accessor: "c"
},
{
Header: "d",
accessor: "d"
}
];
class Table extends React.Component {
state = {
columns: this.props.columns,
data: this.props.data
};
componentWillReceiveProps(nextProps) {
if (nextProps.expand !== this.props.expand) {
console.log("update data");
this.setState({
columns: [...nextProps.columns],
data: [...nextProps.data]
});
}
}
render() {
console.log(this.props.expand);
return (
<div>
{this.props.expand ? (
<ReactTable
data={this.state.data}
columns={this.state.columns}
showPagination={false}
defaultPageSize={data.length}
resizable={false}
SubComponent={row => {
return (
<div>
<h1>expanded state</h1>
</div>
);
}}
/>
) : (
<ReactTable
data={data}
columns={columns}
showPagination={false}
defaultPageSize={data.length}
resizable={false}
/>
)}
</div>
);
}
}
class App extends React.Component {
state = {
expand: true
};
componentDidMount() {
const that = this;
setTimeout(() => {
that.setState({ expand: false });
}, 2000);
}
render() {
const { expand } = this.state;
return (
<div>
<Table columns={columns} data={data} expand={expand} />
<br />
<Tips />
<Logo />
</div>
);
}
}
render(<App />, document.getElementById("root"));
答案 0 :(得分:1)
在源代码中,您应该能够重置SubComponent,但不要将其设置为undefined(这与props如何在props中未定义状态不会覆盖状态有关)。
将SubComponent设置为null或false将得到desired results
class Table extends React.Component {
render() {
console.log("props:", this.props);
return (
<div>
<ReactTable
data={this.props.data}
columns={this.props.columns}
showPagination={false}
defaultPageSize={this.props.data.length}
resizable={false}
SubComponent={
this.props.expand
? row => (
<div>
<h1>expanded state</h1>
</div>
)
: false
}
/>
</div>
);
}
}