本文介绍了反应的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是新手,我不知道如何使用全局变量.我想将"this.props.topic.text"设置为全局变量,以在项目的其他应用程序上使用它.我该怎么办?

Hi guys I'm still new to react and i don't know, how to use 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,
};

推荐答案

这是一个糟糕的主意,但在React中使用全局变量的最好/最简单的方法可能是将其放在window上.在组件中,您可以执行类似window.topicText="some text"的操作,然后在其他任何地方通过window.topicText访问它.

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.

理想情况下,如果您有数据,并且在可能的状态下,您需要在组件之间持久化,则应查看类似 Redux 通量.我更喜欢Redux.

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.

这篇关于反应的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:34