Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - Global variable for react

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,
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...