今天主要記錄一下react native的幾種傳值方式;
1.navigator傳值
在此就不記錄react-navigation
的具體使用方法了,可以參見官網(wǎng)中的使用實(shí)例.下面代碼記錄從home
頁(yè)面跳轉(zhuǎn)到second
頁(yè)面并傳遞參數(shù)的過程;
home頁(yè)面代碼
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={styles.buttonStyle} onPress={() => {this.props.navigation.navigate('second',{datasource: "我是第一個(gè)頁(yè)面?zhèn)鱽淼臄?shù)據(jù)"})}}>
<Text style={{fontSize:16,color:'white'}}>跳轉(zhuǎn)到下一頁(yè)面</Text>
</TouchableOpacity>
</View>
);
}
上面代碼中onPress={() => {this.props.navigation.navigate('second',{datasource: "我是第一個(gè)頁(yè)面?zhèn)鱽淼臄?shù)據(jù)"})}}
就是聲明的一個(gè)跳轉(zhuǎn)的點(diǎn)擊方法,navigator
后面跟的第一個(gè)參數(shù)second
,代表跳轉(zhuǎn)的頁(yè)面;{datasource: "我是第一個(gè)頁(yè)面?zhèn)鱽淼臄?shù)據(jù)"}
代表要傳遞過去的參數(shù),名稱可以是任意,只要保證在另外一個(gè)頁(yè)面取值時(shí)相同即可.當(dāng)然也可以傳遞一個(gè)json字符串,在另外一個(gè)頁(yè)面通過點(diǎn)語(yǔ)法獲取想要的值即可.
接下來看一下在另外一個(gè)頁(yè)面的使用情況
render() {
//1.不同頁(yè)面之間使用navigator進(jìn)行正向傳值
//此處為析構(gòu)的過程,當(dāng)然也可以在在下面直接使用this.props.navigation.state.datasource來獲取,只不過使用這種方式會(huì)更加清晰明了
const { params } = this.props.navigation.state;
return (
<View style={styles.container}>
<Text>{params.datasource}</Text>
</View>
);
}
2.props傳值(一般使用在父子關(guān)系的組件中)
首先來寫一個(gè)子組件(注意次處的子組件和父組件是是在一個(gè)js文件中,若在兩個(gè)js文件中記得使用export default
關(guān)鍵字修飾)
class OneView extends Component {
render(){
return(
<View>
<Text>{this.props.textnum}</Text>
</View>
);
}
}
父組件中使用時(shí)只要傳一個(gè)textnum
,子組件就可以通過他的props
來獲取
<OneView textnum="str"/>
3.ref傳值(一般使用在兄弟組件或者在父組件中對(duì)子組件局部刷新)
把上面寫的OneView
的組件做如下修改
class OneView extends Component {
constructor(props) {
super(props);
this.state = {
//聲明一個(gè)refNum變量并設(shè)初始值為0
refNum : 0,
}
//this._oneFunction = this._oneFunction.bind(this);
}
//在此寫一個(gè)方法,在外面通過ref的方式來調(diào)用,更新當(dāng)前的refNum字段
_oneFunction = (number) => {
this.setState({refNum:number})
}
render(){
return(
<View>
{/*在此驗(yàn)證上面的方法是否執(zhí)行*/}
<Text>{this.state.refNum}</Text>
<Text>{this.props.textnum}</Text>
</View>
);
}
}
在外面使用時(shí)
export default class second extends Component {
render() {
return (
<View style={styles.container}>
{/*點(diǎn)擊方法中通過refs.'設(shè)置的ref值'并通過點(diǎn)語(yǔ)法調(diào)用組件中的方法*/}
<TouchableOpacity style={styles.buttonStyle} onPress={() => {this.refs.OneView._oneFunction(7)}}>
<Text style={{fontSize:16,color:'white'}}>我是home的二級(jí)頁(yè)面</Text>
</TouchableOpacity>
{/*設(shè)置組件的ref值,其實(shí)就是相當(dāng)于設(shè)置一個(gè)索引,在其他的地方可以通過此值來當(dāng)?shù)喇?dāng)前的組件*/}
<OneView ref="OneView" textnum="str"/>
</View>
);
}
}