admin管理员组

文章数量:1193955

I don't know, how to use a global variable.

I want to make "this.props.topic.text" a global variable to use it on an other app of my project. How can I do that?

export default class Topic extends Component {

  deleteThisTopic() {
    Topics.remove(this.props.topic._id);
  }

  test() {
  
  }
  render() {
    return (

      <Router>
    <div>
      <ul>
        <Link to="/sub"><li onClick={this.test.bind(this)}>{this.props.topic.text}  ARN:  {this.props.topic.arn}</li></Link>
        <Link to="/log"><button onClick={this.test.bind(this)}>S'inscrire</button></Link>
        <Link to="/"><button >Cacher</button></Link>
        <button onClick={this.deleteThisTopic.bind(this)}>Suprimer</button>
      </ul>

      <hr/>
      <Route exact path="/log" component={AppInscription}/>
      <Route exact path="/sub" component={AppSub}/>


    </div>
  </Router>
  );
  }
}

Topic.propTypes = {

  topic: PropTypes.object.isRequired,
};

I don't know, how to use a global variable.

I want to make "this.props.topic.text" a global variable to use it on an other app of my project. How can I do that?

export default class Topic extends Component {

  deleteThisTopic() {
    Topics.remove(this.props.topic._id);
  }

  test() {
  
  }
  render() {
    return (

      <Router>
    <div>
      <ul>
        <Link to="/sub"><li onClick={this.test.bind(this)}>{this.props.topic.text}  ARN:  {this.props.topic.arn}</li></Link>
        <Link to="/log"><button onClick={this.test.bind(this)}>S'inscrire</button></Link>
        <Link to="/"><button >Cacher</button></Link>
        <button onClick={this.deleteThisTopic.bind(this)}>Suprimer</button>
      </ul>

      <hr/>
      <Route exact path="/log" component={AppInscription}/>
      <Route exact path="/sub" component={AppSub}/>


    </div>
  </Router>
  );
  }
}

Topic.propTypes = {

  topic: PropTypes.object.isRequired,
};

Share Improve this question edited Jan 6, 2021 at 23:51 peterh 12.6k20 gold badges89 silver badges113 bronze badges asked Jul 13, 2017 at 12:00 alpheonixalpheonix 3132 gold badges5 silver badges13 bronze badges 4
  • 1 It's not clear at all why you think you need a global variable. What is the relationship between the code you have posted and the question you have asked? – Tom Fenech Commented Jul 13, 2017 at 12:21
  • i have an other app on my project in which i need to use the variable returned by "this.props.topic.text". I think the only way to get this variable on my other app is to make her became global so my question is how to define a global variable in react and how i can use it ? – alpheonix Commented Jul 13, 2017 at 12:27
  • You can't really define properties as global in react but you can use a library like redux to have one single state for your entire application where you can access the object from different places. – user5692355 Commented Jul 13, 2017 at 12:39
  • I guess you might be right @Alex but if the OP is really talking about completely separate apps, then maybe they just want to write a value to a file. I still don't understand the requirement. – Tom Fenech Commented Jul 13, 2017 at 12:47
Add a comment  | 

6 Answers 6

Reset to default 12

It is a terrible idea, but probably the best/easiest way to use a global variable in React is to put it on the window. In a component you could do something like window.topicText="some text" and then access it via window.topicText everywhere else.

Ideally, if you have data, and in your case likely state, that you need to persist from component to component, you should look into something like Redux or Flux. I prefer Redux.

You can try this: Declare your global variable before your main component App.js and pass this variable as props down the tree.

Parent.js

var myVar = {}

class MyComponent extends Component {

...
...
myVar = new Object();
...
...
render() {
   return <div>
                 \\ children
                 <MyLeftBranch myVar={myVar} />
                 <MyRightBranch myVar={myVar} />
              </div>
}
}

export default MyComponent;

child.js

class Child extends Component {
     { myVar } = this.props;
     \\use myVar
}

TypeScript + globalThis

//@ts-ignore TODO cleanup this debug output
globalThis.MY_NAMESPACED_NAME = { something: 'to inspect in the console' }

A bad idea for production code, but useful for debugging.

App.js

// Since this.state is global from parent to child components
// This was the easiest solution I've found:

import React, { Component } from "react";
import firebase from "../config";

class App extends Component
 constructor(props) {
     super(props);

     // Set the key to the reference name
     // Assign value to firebase DB collection

     this.state = {
         roomsRef: firebase.firestore().collection("rooms")
     }
}

// reference it anywhere in the component:

componentDidMount() {
    this.getDb(this.state.roomsRef);
}

Depending on your use case, a good way to use global variables is Context. Basically, what a Context is doing, offers the possibility for every component to access a set of variables everywhere in the code. (Normally, the way variables are passed, is from parent to child)

For reference: https://reactjs.org/docs/context.html

To use a global variable, I found a below way : 

    Create a file :
    
    import React from "react";
    
    const AppContext = {};
    
    export default AppContext;
    
    then in App.js, update the value
    import AppContext from './AppContext';
    
    
    AppContext.username = uname.value;
    
    Now if you want the username to be used in another screen:
    
    import AppContext from './AppContext';
    
    AppContext.username to be used for accessing it.


I found another way also ,using localStorage to use it anywhere in the application :

1)Setting the value : 
  localStorage.setItem('username', <set the name>);

2)Getting the value :
localStorage.getItem("username")

本文标签: javascriptGlobal variable for reactStack Overflow