【发布时间】:2021-01-02 13:56:04
【问题描述】:
我有两个组件,一个用于从两个输入字段获取 JSON 数据,另一个用于显示收集的数据并将其用于不同目的。从 JSON 文件中获取数据后,我将它们设置为第一个组件的状态。
我的问题是如何将在第一个组件中获得的设置为状态的数据发送到另一个组件,以便我可以在第二个组件中以表格的形式显示数据。
第一个组件:
export class comp extends Component {
constructor(props) {
super(props);
this.state = {
uploadfile1:null,
uploadfile2:null
}
this.readFile = this.readFile.bind(this);
}
readFile(e) {
{/*Reading JSON Files*/}
const file = e.target;
const fileId = file.id;
if (/\.(json)$/i.test(file.files[0].name) === false) {
alert("Not valid JSON file!");
}
else {
const fileReader = new FileReader();
fileReader.readAsText(file.files[0], "UTF-8");
fileReader.onload = () => {
console.log(fileReader.result);
const data = JSON.parse(fileReader.result);
this.setState({
['upload' + fileId]: data
})
};
}
}
render() {
return (
<div className="new-audit-content-wrapper">
<input onChange={this.readFile} type="file" id="file1" className="inputfile"/>
<label htmlFor="file1">Browse for files</label>
<input onChange={this.readFile} type="file" id="file2" className="inputfile"/>
<label htmlFor="file2">Browse for files</label>
</div>
)
}
}
第二个组件;
export class table extends Component {
render() {
return (
<div className="wrapper">
<thead className="table-head">
<tr className="table-head-cols">
<th className="col-1">Seq#</th>
<th className="col-2">Data Audit Row #</th>
</tr>
</thead>
<tbody className="table-body">
<tr className="table-body-cols">
<td className="table-body-col-1">1</td>
<td className="table-body-col-2">3</td>
</tr>
</tbody>
</div>
)
}
}
我只需要使用 Props 将数据从第一个组件状态传递到第二个组件吗?我不知道确切的解决方案,因为我是新手。
谢谢
【问题讨论】:
标签: javascript html css reactjs react-props