大家好,我还是新手,我不知道如何使用全局变量。我想将“ this.props.topic.text”设置为全局变量,以在项目的其他应用程序上使用它。我怎样才能做到这一点 ?
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其他任何地方进行访问。
window
window.topicText="some text"
window.topicText
理想情况下,如果您有数据,并且在可能的状态下,需要在各个组件之间进行持久化,则应考虑使用Redux或Flux之类的东西。我更喜欢Redux。