反应出口数据

时间:2018-05-28 09:58:30

标签: javascript reactjs

您好,请检查以下代码,

import React, { Component } from 'react';
let ok;
class Mydata extends Component {
    constructor() {
        super();
        this.state = {
          rif: [{
              "instituteName": "SEVILLE SCHOOL AND COLLEGE",
              "instituteAddress": "BALUBARI, SADAR, DINAJPUR"   
          } ]                      
        };
    }

render() {   
console.log(this.state.rif); 
  return (
      <div>
 check Console Log
     </div>
  );
  }
}

export default Mydata; 

我在this.state.rif保留一些值。我需要将此值保持为全局值,并希望将此this.state.rif导出到另一个组件以供重用。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

您可以使用父子方法

来实现

Mydata.js 文件

import NewComponent from './newComponent.js';

class Mydata extends Component {
    constructor() {
        super();
        this.state = {
          rif: [{
              "instituteName": "SEVILLE SCHOOL AND COLLEGE",
              "instituteAddress": "BALUBARI, SADAR, DINAJPUR"   
          } ]                      
        };
    }

render() {   
console.log(this.state.rif); 
  return (
      <div>
 Parent Component
    <NewComponent rif={this.state.rif} />
     </div>
  );
  }
}

export default Mydata; 

另一个组件newComponent.js

class NewComponent extends Component {

render() {   
console.log(this.props.rif); 
  return (
      <div>
 check Console Log newComponent
     </div>
  );
  }
}

export default NewComponent; 

答案 1 :(得分:0)

  • 子组件的父组件:使用Prop
  • 子组件到父组件:使用回调和状态

答案 2 :(得分:0)

//moduleA.js
let object = {
    rif: 5,
};

export { object };

//MyData.js
import { object } from './moduleA'

class Mydata extends Component {
object.rif=this.state.rif;
}