界面與界面之間的傳值
事件監(jiān)聽(通知)
import {
DeviceEventEmitter
} from 'react-native';
componentDidMount() {
this.event = DeviceEventEmitter.addListener("onClickButton", (text,...) => { //注冊(cè)通知
console.log(text);
this.onClickAddButton(text)
});
}
componentWillUnmount(){
// 移除通知
this.listener.remove();
}
//發(fā)送通知 第一個(gè)參數(shù)是通知名稱,后面的參數(shù)是發(fā)送的值可以多個(gè)
DeviceEventEmitter.emit('onClickButton','test',...)
事件回調(diào)(類與類之間的傳值)
通過navigation帶過去的參數(shù)實(shí)現(xiàn)事件回調(diào),類似于OC的block,使用方法如下
A.js
this.props.navigation.push('A', { title:'個(gè)人信息', callback:(msg)=>{ alert(msg) } }) //第一個(gè)參數(shù)是需要調(diào)整的路由名稱,第二個(gè)參數(shù)就是傳過去的參數(shù)。
B.js
this.props.navigation.state.params.callback('反向傳值的參數(shù)')
this.props.navigation.state.params.title //正向傳值
屬性傳值(組件與組件之間的傳值)
import React,{Component} from 'react';
import {View,Text, AppRegistry, Button, StyleSheet,TouchableOpacity,Image,FlatList} from 'react-native';
export default class ValueView extends Component {
render(){
return (
<View style={{flex: 1}}>
<SuperView testTitle='這是一個(gè)測(cè)試'/>
</View>
);
}
}
class SuperView extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{flex: 1, alignItems: 'center'}}>
<SubView
onclickFunction={this.onclickFunction.bind(this)}
ref="son" />
</View>
);
}
onclickFunction(text){
this.refs.son.receiveMoney(1000);
console.log(this.props.testTitle);
console.log(text);
}
}
class SubView extends Component {
render() {
return (
<View>
<TouchableOpacity
onPress={this._onPress}
style={{backgroundColor: 'red', alignSelf: 'center'}}>
<Text>
點(diǎn)擊回傳結(jié)果
</Text>
</TouchableOpacity>
</View>
);
}
receiveMoney(money){
console.log(money);
}
_onPress = () => {
this.props.onclickFunction('反向傳值') //這里就能調(diào)用父組件的onclickFunction(text)方法
}
}
注意:
1.屬性傳值只能用于父子組件之間的傳值,如果要無關(guān)的組件傳值或者是跨組件傳值的話目前只能使用事件監(jiān)聽(通知)的方式
2.<SubView ref="son" />相當(dāng)于是把SubView組件添加了一個(gè)標(biāo)記son然后綁定到了ref上面,我們通過this.refs.son就可以直接獲取到SubView這個(gè)對(duì)象 即SubView的this = this.refs.son。