提问者:小点点

在React中将状态数据从一个组件传递到另一个组件


我有两个组件,一个用于从两个输入字段获取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>
        )
    }
}

我必须使用道具将数据从第一个组件状态传递到第二个组件?我不知道确切的答案,因为我是新的反应。

谢啦


共3个答案

匿名用户

您需要将数据作为道具传入,并将“第二组件”作为“第一组件”的子组件包括在内。

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

匿名用户

您可以发送一个函数作为道具,并使用它来更新父组件中的数据。看看这个例子:

父母亲JSX

import React, { useState } from 'react';
import Child from './Child'

export default () => {

  const [updateValue, setUpdateValue] = useState('Initial Value')

  const parentFunction = (e) => {
    console.log(e.target.value)
    setUpdateValue(e.target.value)
  }

  return (
    <>
      <h1>{updateValue}</h1>
      <Child parentData="Parent Data" updateValue={parentFunction} />
    </>
  )
}

Child.jsx

import React from 'react';

export default ({parentData, updateValue}) => {
  return (
    <>
      <h2>{parentData}</h2>
      <input type="text" onChange={(e) => updateValue(e)} />
    </>
  )
}

匿名用户

将第二个组件更改为功能组件,从道具接收数据,并使用数据呈现标记:

export function Table (props) {
const {data} = props
  
        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">
                      {/* You can use your data here to render the table rows */}
                            <tr className="table-body-cols">
                                <td className="table-body-col-1">1</td>
                                <td className="table-body-col-2">3</td>
                            </tr>
                            
                        </tbody>
                         
            </div>
        )
    
}

在第一个组件中,导入第二个组件

import Table from "../component/Table"

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>

                 <Table data={this.state.data} />
            </div>
        )
    }
}