我是新的反應本地開發。我有3個組件。最初第一個組件被加載。從1個組件推到2個組件並再次從2個組件推到3個組件。如果3組件我正在做一些更改,同時我想刷新1 & 2組件。當我點擊後退按鈕不刷新。如何刷新它?一對多組件之間的通信反應本地
1 component ==> 2 component ==> 3 component (if login is success how can i refresh back component method)
我是新的反應本地開發。我有3個組件。最初第一個組件被加載。從1個組件推到2個組件並再次從2個組件推到3個組件。如果3組件我正在做一些更改,同時我想刷新1 & 2組件。當我點擊後退按鈕不刷新。如何刷新它?一對多組件之間的通信反應本地
1 component ==> 2 component ==> 3 component (if login is success how can i refresh back component method)
您可以將數據傳遞到一個組件到另一個通過使用道具
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class ComponentOne extends Component {
render(){
return(
<ComponentTwo
text="Hello"
/>
)
}
}
class ComponentTwo extends Component {
render(){
return(
<ComponentThree
textTwo={this.props.text}
/>
)
}
}
class ComponentThree extends Component {
render(){
return(
<View><Text>{this.props.textTwo}</Text></View>
)
}
}
欲瞭解更多詳情,請參閱此鏈接http://facebook.github.io/react-native/releases/0.45/docs/props.html#props
陣營的基本思路是向下的數據流。該狀態應該保存在父組件中並向下流向子組件。當你想從一個子組件改變狀態時,你需要將狀態提升回父組件。
這裏很重要的一個概念是組件類型之間的區別:智能與啞巴或表示與容器。基本上,智能/容器組件持有狀態和邏輯,啞/表示組件只呈現UI。這裏是一個偉大的文章:
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
而且,在作出反應和應對本地的,部件不完全刷新。有一個稱爲diffing的過程,在此過程中獲取了前一個DOM樹的快照,並與具有下一個狀態道具的DOM樹進行比較,僅顯示更改。所以,你所要做的就是改變父/智能/容器組件中的狀態,React將通過差異來照顧重新渲染。
所以,這樣的事情會做的伎倆:
import React, { Component } from 'react';
import { View, StyleSheet, Button, Text } from 'react-native';
import { Constants } from 'expo';
export default class Parent extends Component {
state = { isLoggedIn: false, otherState: '' }
_handleLogin =() => {
//do login stuff
this.setState({ isLoggedIn: true });
}
render() {
return (
<View style={styles.container}>
<ChildOne handleLogin={this._handleLogin} {...this.state} />
{this.state.isLoggedIn &&
<Text>Now logged in!</Text>
}
</View>
)
}
}
const ChildOne = props => (
<View>
<Grandchild {...props} />
</View>
);
const Grandchild = props => (
<Button
onPress={() => props.handleLogin()}
title="some title"
/>
)
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
}
});
這裏是小吃,你可以看到它在設備上: https://snack.expo.io/SkhOTvkVb
你應該閱讀的https://facebook.github .io/react/docs/lifting-state-up.html或者使用更好的解決方案,即redux。 –