简体   繁体   English

访问从一个组件到另一个组件的数据

[英]Accessing the data from one component to another component

Hi I am starting to learn reactjs. 嗨,我开始学习reactjs。 So after understanding the basics Im starting to work on database connectivity using reactjs. 因此,在了解了基础知识后,我开始使用reactjs来处理数据库连接。 In the code Im trying to get the userId and Password to establish a DB connectivity and trying to list the tables available in the DB. 在代码中我试图获取userId和Password来建立数据库连接并尝试列出数据库中可用的表。 In the Login.js I have create a form (userId and Password) when login button is clicked I will make a connectivity and execute the Show Table query to list all the tables in the DB, and move to the Table.js page where I try to list the available tables. 在Login.js中,我在单击登录按钮时创建了一个表单(userId和Password)我将建立连接并执行Show Table查询以列出数据库中的所有表,并移动到Table.js页面,在那里我尝试列出可用的表。 Right now I able to connect to the DB but not able to display the tables in the Table.js , so how to display the tables list in the Table.js file, because I have placed my DB connectivity and query inside a button event in the Login.js. 现在我能够连接到DB而不能显示Table.js的表,所以如何在Table.js文件中显示表列表,因为我已将我的数据库连接和查询放在一个按钮事件中Login.js。 Also Is there a possible to declare a variable global and access it across the another js files. 还有可能声明一个变量全局并跨另一个js文件访问它。 Any help would be great, thank you. 任何帮助都会很棒,谢谢。

Login.js Login.js

import React from 'react';
import TableContent from './tables';
class Login extends React.Component{
    constructor(){
        super();
        this.state={
            showComponent : false,
        };
        // this.buttonClick = this.buttonClick.bind(this);
    }

    buttonClick(event){
        event.preventDefault();
        this.setState({
            showComponent: true,
        })

        var db = require('@dataBase/dynamoConnect')({
            "UserId": "XXXXXXXXXXXXXXXXXXXXXXXX",
            "Password": "YYYYYYYYYYYYYYY",
            "region": "ZZZZZZZZZZ"
        });
        db.query("SHOW TABLES",(err,data)=>{
        const tableList = data;
        console.log(tableList);
        })
    }
    render(){
        return(
            <div>
                <form>
                    <label>User Id :</label>
                    <input type="text" className="test"/>
                    <br/>
                    <label>Password :</label>
                    <input type="text" className="test" />
                    <button onClick={this.buttonClick.bind(this)} className="connect" > Login</button>
                  </form>
                 {this.state.showComponent && <TableContent />}
            </div>  
        )
    }
}

export default Login;

Table.js Table.js

import React from 'react';

class TableContent extends React.Component {
    constructor() {
        super();
        this.state = {
            showComponent: false,
        };
        this.buttonClick = this.buttonClick.bind(this);
    }

    buttonClick(event) {
        event.preventDefault();
        this.setState({
            showComponent: true,
        })
    }

    render() {
        return (
            <div>
                <form>
                 <div id="first">   
                <label> Table </label>
                <br />
                //Display the tables from DB here
                <select name="sometext" multiple="multiple" >
                    <option>Table1</option>
                    <option>Table2</option>
                    <option>Table3</option>
                    <option>Table4</option>
                    <option>Table5</option>
                </select>
                </div>
                <div id="second"> 
                <label> SQL </label>
                <br/>
                <textarea rows="4" cols="50">SQL </textarea>
                </div>
                <button onClick={this.buttonClick.bind(this)} > Execute </button> 
                <div id="third" >
                {this.state.showComponent && <SampleTable />}
                </div>
                </form>
            </div>
        )
    }
}

export default TableContent;

There are a number of strategies for communicating between components, but the easiest way (without using Flux or Redux) is to use a parent component to act as a mediator for the communication. 组件之间有许多通信策略 ,但最简单的方法(不使用Flux或Redux)是使用父组件充当通信的中介。

Basically, the parent passes a callback to one component that sets some state to pass down the the other component, for example: 基本上,父级将回调传递给一个组件,该组件将某个状态设置为传递给另一个组件,例如:

Child creating data 孩子创建数据

class Child1 extends React.Component {
  constructor() {
    super()
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.props.setMessage("hello world")
  }

  render() {
    return <button onClick={this.handleClick}>say hello</button>
  }
}

Child using data 孩子使用数据

const Child2 = ({message}) => {
  return <p>{message}</p>
}

Parent

class Parent extends React.Component {
  constructor() {
    super()
    this.state = { message: "" }
  }

  render() {
    return (
      <div>
        <Child1 setMessage={(message) => this.setState({ message })} />
        <Child2 message={this.state.message} />
      </div>
    )
  }
}

If they can't be siblings, this pattern can get a bit strenuous, but can still be achieved by having the mediator component as the lowest common ancestor and passing the relevant props all the way down. 如果他们不能成为兄弟姐妹,这种模式可能会有点费劲,但仍然可以通过将中介组件作为最低共同祖先并将相关道具一直向下传递来实现。 At that point though, you may want to investigate Flux or Redux and externalising the state from the components entirely. 但是,在那时,您可能需要调查Flux或Redux并完全从组件外部化状态。

First. 第一。

The Table.js component need to know the data to display. Table.js组件需要知道要显示的数据。
1 - you have to save result of the query in component state, by calling this.setState({tableData: tableList}) in query callback: 1 - 您必须通过在查询回调中调用this.setState({tableData: tableList})来保存组件状态中的查询结果:

db.query("SHOW TABLES",(err,data)=>{
  const tableList = data;
  this.setState({
    tableData: tableList,
  });
})  

2 - you need to pass saved result as a property to TableContent , like this: 2 - 您需要将保存的结果作为属性传递给TableContent ,如下所示:

in Login.js : Login.js
{this.state.showComponent && <TableContent data={this.state.tableData} />} ; {this.state.showComponent && <TableContent data={this.state.tableData} />} ;

3 - render data in the child component. 3 - 渲染子组件中的数据。 You can get access to it via this.props.data . 您可以通过this.props.data访问它。 You can iterate over an result array and render all table rows in single loop. 您可以迭代结果数组并在单循环中呈现所有表行。 Take a look at this react doc . 看看这个反应文档

Second: 第二:

Also Is there a possible to declare a variable global and access it across the another js files 还有可能声明一个变量全局并跨另一个js文件访问它

In short - yes. 简而言之 - 是的。 You can export functions, variables, classess from your module. 您可以从模块中导出函数,变量,classess。

Small example: 小例子:

// scriptA.js;
export const a = 42;

// scriptB.js;
import { a } from 'path/to/scriptA.js';
console.log(a) // will print 42;

This example assumes you are using es6 import/export feature. 此示例假定您使用的是es6导入/导出功能。 You can require it as well. 你也可以require它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM