Ger*_*ate 69
React Native中的全局范围是可变全局的.比如global.foo = foo,那么你可以在任何地方使用global.foo.
但是不要滥用它!在我看来,全局范围可能用于存储全局配置或类似的东西.在不同视图之间共享变量,作为您的描述,您可以选择许多其他解决方案(使用redux,flux或将它们存储在更高的组件中),全局范围不是一个好的选择.
定义全局变量的一个好习惯是使用js文件.例如global.js
global.foo = foo;
global.bar = bar;
Run Code Online (Sandbox Code Playgroud)
然后,确保在项目初始化时执行它.例如,在index.js中导入文件:
import './global.js'
// other code
Run Code Online (Sandbox Code Playgroud)
现在,您可以在任何地方使用全局变量,而不需要在每个文件中导入global.js.尽量不要修改它们!
sti*_*des -3
例如,您应该在 React Native 中执行此操作的方式(据我所知)是将“全局”变量保存在 index.js 中。从那里你可以使用道具将其传递下去。
例子:
class MainComponent extends Component {
componentDidMount() {
//Define some variable in your component
this.variable = "What's up, I'm a variable";
}
...
render () {
<Navigator
renderScene={(() => {
return(
<SceneComponent
//Pass the variable you want to be global through here
myPassedVariable={this.variable}/>
);
})}/>
}
}
class SceneComponent extends Component {
render() {
return(
<Text>{this.props.myPassedVariable}</Text>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78878 次 |
| 最近记录: |