美文网首页
reactNative 之组件传值和反向传值

reactNative 之组件传值和反向传值

作者: Lucky_1122 | 来源:发表于2017-08-08 10:29 被阅读359次

在项目中我们经常会遇到传值,传值有正向传值和反向传值,比如
1.正向传值:从A组件push到B组件传值
2.反向传值:从A组件push到B组件,然后在B组件修改数据之后,想要在A组件更新显示,这时候就需要反向传值告诉A组件。
实现反向传值:在A组件进行this.props.navigation.navigate()的时候传参数增加一个函数getName就像这样:

this.props.navigation.navigate('MNickName',
                                    {
                                        name:that.state.subtitles[i],
                                        getName:function(name){
                                        console.log(that.state.subtitles);
                                        let subtitls= that.state.subtitles.splice(0,1,name);
                                        console.log(that.state.subtitles);
                                        that.setState({name:name,subtitles:that.state.subtitles})
                                    }}
                                    )

然后在B组件需要返回传值的时候调用getName方法就可以传值过来了:

 static navigationOptions = ({navigation}) => ({

        headerTitle: '修改用户名',
        headerLeft: (
            <NavigationItem
                icon={require('../../img/Public/back.png')}
                onPress={() => navigation.goBack()}
            />
        ),
        headerRight: (
            <Button
                style={{color: color.theme, fontSize: 15, marginRight: 10, fontWeight: 'bold'}}
                title="确定"
                onPress={() => {
                    const {params} = navigation.state;
                    params.getName(_this.state.text);
                    navigation.goBack()
                }}
            />
        ),
        headerStyle: {backgroundColor: 'white'}
    })

下面展示下反向传值:


ezgif.com-gif-to-apng.gif

下面附上源码:
A组件为个人信息:
MineInfo

import React, { PureComponent } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    TextInput,
    ScrollView,
    FlatList,
    SectionList,
    RefreshControl,
    TouchableOpacity,
    ActionSheetIOS,

} from 'react-native';
import NavigationItem from '../../widget/NavigationItem';
import  color from '../../widget/color';
import MineItemAvatar from './MineItemAvatar';
import MineBaseInfo from './MineBaseInfo';

export default class  MineInfo extends PureComponent{
    static navigationOptions = ({navigation})=>({
        headerTitle:'个人信息',
        headerLeft:(
            <NavigationItem
                icon={require('../../img/Public/back.png')}
                onPress={()=>{
                    navigation.goBack();
                }}
            />
        ),

    })

    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            titles:['昵称','生日','收货地址'],
            subtitles:['123','19900101','上海市'],
            name:''
        };

      }


    render(){
        let that = this;
        return(
            <ScrollView>
                <MineItemAvatar
                    title='头像'
                    icon={require('../../img/Mine/avatar.png')}
                    onPress={()=>{
                        ActionSheetIOS.showActionSheetWithOptions({
                                options: ['拍照', '从手机相册选择', '取消'],
                                cancelButtonIndex:2
                            },(buttonIndex)=>{
                            alert(buttonIndex);
                            }
                        )
                    }}
                />
                {this.state.titles.map((title,index)=>(
                    <MineBaseInfo
                        title={title}
                        subtitle={this.state.subtitles[index]}
                        key={index}
                        selectedIndex={index}
                        onPress={(i)=>{
                            if(i==0){
                         {this.props.navigation.navigate('MNickName',
                                    {
                                        name:that.state.subtitles[i],
                                        getName:function(name){

                                        console.log(that.state.subtitles);
                                        let subtitls= that.state.subtitles.splice(0,1,name);
                                        console.log(that.state.subtitles);
                                        that.setState({name:name,subtitles:that.state.subtitles})
                                    }}


                                    )}
                            }


                        }}
                    />
                ))}
            </ScrollView>
        );
    }
}

由于下面三行是重复部分 抽出出来
MineBaseInfo代码如下:


import React, { PureComponent } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    TextInput,
    ScrollView,
    FlatList,
    SectionList,
    RefreshControl,
    TouchableOpacity,

} from 'react-native';
import NavigationItem from '../../widget/NavigationItem';
import  color from '../../widget/color';
import {Heading1} from '../../widget/Text';
import {Heading2,Paragraph} from '../../widget/Text';
import Seprator from '../../widget/Separator';
export default class MineBaseInfo extends PureComponent{
    render(){
        let index = this.props.selectedIndex;
        return(
            <TouchableOpacity onPress={()=>this.props.onPress(index)}>
                <View style={styles.container} >
                    <Heading2 style={{marginLeft:15}}>{this.props.title}</Heading2>
                    <View style={styles.rightContainer}>
                        <Paragraph>{this.props.subtitle}</Paragraph>
                        <Image source={require('../../img/Public/cell_arrow.png')} style={styles.arrow}/>
                    </View>
                </View>
                <Seprator/>
            </TouchableOpacity>
        );
    }
}
const styles = StyleSheet.create({
    container:{
        backgroundColor:'white',
        flexDirection:'row',
        // justifyContent:'center',
        alignItems:'center',
        paddingVertical:20

    },
    rightContainer:{
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'flex-end',
        marginRight:15,
    }
    ,
    avatar:{
        width:30,
        height:30,
        borderRadius:15,
        marginRight:5
    },
    arrow:{
        width:10,
        height:10
    }
})

第一行显示头像的组件
MineItemAvatar源码如下:


import React, { PureComponent } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    TextInput,
    ScrollView,
    FlatList,
    SectionList,
    RefreshControl,
    TouchableOpacity,

} from 'react-native';
import NavigationItem from '../../widget/NavigationItem';
import  color from '../../widget/color';
import {Heading1} from '../../widget/Text';
import {Heading2} from '../../widget/Text';
import Seprator from '../../widget/Separator';

export default class MineItemAvatar extends PureComponent{
    render(){
        return(
            <View>
            <TouchableOpacity style={styles.container} onPress={this.props.onPress}>
                <Heading2 style={{marginLeft:15}}>{this.props.title}</Heading2>
                <View style={styles.rightContainer}>
                    <Image source={this.props.icon} style={styles.avatar}/>
                    <Image source={require('../../img/Public/cell_arrow.png')} style={styles.arrow}/>
                </View>

            </TouchableOpacity>
                <Seprator/>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container:{
        backgroundColor:'white',
        flexDirection:'row',
        // justifyContent:'center',
        alignItems:'center',
        paddingVertical:10

    },
    rightContainer:{
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'flex-end',
        marginRight:15,
    }
    ,
    avatar:{
        width:30,
        height:30,
        borderRadius:15,
        marginRight:5
    },
    arrow:{
        width:10,
        height:10
    }
})

B组件源码如下:
ModifyUserNickName


import React, { PureComponent } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    TextInput,
    ScrollView,
    FlatList,
    SectionList,
    RefreshControl,
    TouchableOpacity,
    ActionSheetIOS,

} from 'react-native';
import NavigationItem from '../../widget/NavigationItem';
import  color from '../../widget/color';
import Button from '../../widget/Button';
import {Heading1,HeadingBig} from '../../widget/Text';
import {Heading2,Paragraph} from '../../widget/Text';
import screen from '../../common/screen';
let _this ;
export default class  ModifyUserNickName extends PureComponent {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            text: '',
            color: color.border
        }
        _this = this;
    };
    static navigationOptions = ({navigation}) => ({

        headerTitle: '修改用户名',
        headerLeft: (
            <NavigationItem
                icon={require('../../img/Public/back.png')}
                onPress={() => navigation.goBack()}
            />
        ),
        headerRight: (

            <Button
                style={{color: color.theme, fontSize: 15, marginRight: 10, fontWeight: 'bold'}}
                title="确定"
                onPress={() => {
                    const {params} = navigation.state;
                    params.getName(_this.state.text);
                    navigation.goBack()
                }}
            />
        ),
        headerStyle: {backgroundColor: 'white'}
    })

    componentDidMount() {
        const {params} = this.props.navigation.state;
        this.setState({
            text:params.name,
        })
    }
    _onBlur(){


        this.setState({color:color.border});
    }
    render() {

        return (
            <ScrollView >
                <View style={[styles.container,{borderColor:this.state.color}]}>
                    <Heading1 style={{marginRight:5}}>用户名:</Heading1>
                    <TextInput
                        placeholder='请输入用户名'
                        value={this.state.text}
                        onChangeText={(text) => this.setState({text})}
                        style={{fontSize:15,padding:0,flex:1,marginRight:5}}
                        clearButtonMode='while-editing'
                        blurOnSubmit={true}
                        onFocus={()=>{this.setState({color:color.theme})}}
                        onBlur={()=>this._onBlur()}
                    />
                </View>
            </ScrollView>
        )

    }
}
const styles = StyleSheet.create({
    container:{
        flexDirection:'row',
        alignItems:'center',
        backgroundColor:'white',
        padding:15,
        margin:20,
        borderWidth:screen.onePixel,
        borderColor:color.borderColor,
        borderRadius:5,
}
})

相关文章

网友评论

      本文标题:reactNative 之组件传值和反向传值

      本文链接:https://www.haomeiwen.com/subject/elttrxtx.html