我有两个组件,一个组件用于从两个输入字段获取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将数据从第一组件状态传递到第二组件?我不知道确切的解决方案,因为我是新来的反应者。
谢谢
您需要将数据作为道具传递,并将“第二个组件”包括为“第一个组件”的子代。
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>
{/* Add the table below, similar to the example */}
<Table data={this.state.uploadFile1} />
</div>
)
}
我不知道您是否在遵循示例,但是您已经直观地(或开始走路..)进入一种模式:https : //medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句