Javascript 从组件React Native中访问状态
我对react native和使用RkButton然后在单击按钮时更新状态的应用程序相当陌生。代码是这样的Javascript 从组件React Native中访问状态,javascript,reactjs,react-native,components,Javascript,Reactjs,React Native,Components,我对react native和使用RkButton然后在单击按钮时更新状态的应用程序相当陌生。代码是这样的 render(){ const{user}=this.props; 让导航=this.props.navigation.navigate; let items=MainRoutes.map(函数(路由、索引){ 返回( { 这是我的国家({ 救赎:真的 }); }}> ) }); 返回( } contentContainerStyle={styles.rootContainer}> {i
render(){
const{user}=this.props;
让导航=this.props.navigation.navigate;
let items=MainRoutes.map(函数(路由、索引){
返回(
{
这是我的国家({
救赎:真的
});
}}>
)
});
返回(
}
contentContainerStyle={styles.rootContainer}>
{items}
)
}
您在此处失去了组件上下文:
// Component context
function (route, index) {
// Functions context
将其更改为:
(route, index) => {
问题是,用关键字
function
声明的函数有自己的上下文this
。您需要使用箭头函数才能访问父上下文:
let items = MainRoutes.map((route, index) => {
return (
<RkButton
rkType='square'
key={index}
onPress={() => {
this.setState({
redeem: true
});
}}>
</RkButton>
)
});
let items=MainRoutes.map((路线、索引)=>{
返回(
{
这是我的国家({
救赎:真的
});
}}>
)
});
您应该保留一份此的副本,并在任何其他功能中使用它。必要时,如第3行所述
所以你的代码有一些小的改变
render() {
const { user } = this.props;
let self=this;
let navigate = this.props.navigation.navigate;
let items = MainRoutes.map(function (route, index) {
return (
<RkButton
rkType='square'
key={index}
onPress={() => {
self.setState({
redeem: true
});
}}>
</RkButton>
)
});
return (
<View style={{flex: 1,}}>
<ScrollView
alwaysBounceVertical
overScrollMode={"always"}
style={{flex: 1, backgroundColor: 'white'}}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={() => this.handleRefresh()}
/>
}
contentContainerStyle={styles.rootContainer}>
{items}
</ScrollView>
</View>
)
}
render(){
const{user}=this.props;
让自我=这个;
让导航=this.props.navigation.navigate;
let items=MainRoutes.map(函数(路由、索引){
返回(
{
自我状态({
救赎:真的
});
}}>
)
});
返回(
}
contentContainerStyle={styles.rootContainer}>
{items}
)
}
Aha!好的,谢谢!有没有什么时候你想失去这个范围?这仅仅是为了封装吗?@swimming您可能需要释放上下文(抱歉混淆),例如在处理程序中,当您想要引用单击的元素时。例如,在jquery中,$(“a”)。单击(function(){$(this)/*!!*/})
Ah ok,因此当您使用函数(路由、索引)时,此
就是被单击的按钮。谢谢@在这种情况下,swimig可能是窗口
,它实际上没有用处,可能是