我陷入了React的基本原则:/ 有代码生成包含json数据的表:
import React from 'react'
import { DataTable } from 'react-data-components';
function buildTable(data) {
const tableColumns = [
{ title: 'Author', prop: 'author' },
{ title: 'Country', prop: 'country' },
{ title: 'Title', prop: 'title' },
];
return (
<DataTable
className="container"
keys="id"
columns={tableColumns}
initialData={data}
initialPageLength={5}
/>
);
}
let url = 'https://api.myjson.com/bins/1sbz3lp';
fetch(url)
.then(res => res.json())
.then((rows) => {
ReactDOM.render(buildTable(rows), document.getElementById('root'));
});
它可以在index.js
中完成工作但是可以在React组件中呈现表吗?
const Home = () => (
//renders buildTable(rows)
)
export default Home
非常感谢所有可能的帮助,期待。
答案 0 :(得分:1)
您可以将这些行作为主页组件的道具传递,然后执行任何操作。
fetch(url)
.then(res => res.json())
.then((rows) => {
ReactDOM.render(<Home data={rows} />, document.getElementById('root'));
});
现在您可以使用this.props.data
获取行信息,并在组件中的buildTable中执行您正在执行的操作。
import React from 'react'
const Home = () => (
//this.props.data will give you the rows data and do whatever you want here.
//renders buildTable(rows)
)
export default Home
答案 1 :(得分:1)
将buildTable()
移至Home.js
,然后在index.js
中呈现主页组件,将rows
作为道具传递:
<强> Home.js 强>
import React from 'react'
import { DataTable } from 'react-data-components'
function buildTable(data) {
const tableColumns = [
{ title: 'Author', prop: 'author' },
{ title: 'Country', prop: 'country' },
{ title: 'Title', prop: 'title' },
]
return (
<DataTable
className="container"
keys="id"
columns={tableColumns}
initialData={data}
initialPageLength={5}
/>
)
}
const Home = props => buildTable(props.data)
export default Home
<强> index.js 强>
import ReactDOM from 'react-dom'
import Home from './Home'
let url = 'https://api.myjson.com/bins/1sbz3lp'
fetch(url)
.then(res => res.json())
.then(rows => {
ReactDOM.render(<Home data={rows} />, document.getElementById('root'));
})
编辑有状态主页组件
<强> Home.js 强>
import React, { Component } from 'react'
import { DataTable } from 'react-data-components'
const url = 'https://api.myjson.com/bins/1sbz3lp'
class Home extends Component {
state = {
data: []
}
buildTable = (data) => {
const tableColumns = [
{ title: 'Author', prop: 'author' },
{ title: 'Country', prop: 'country' },
{ title: 'Title', prop: 'title' },
]
return (
<DataTable
className="container"
keys="id"
columns={tableColumns}
initialData={data}
initialPageLength={5}
/>
)
}
componentDidMount() {
fetch(url)
.then(res => res.json())
.then((rows) => {
this.setState({ data: rows })
})
}
render() {
return <div>{this.buildTable(this.state.data)}</div>
}
}
export default Home