React-Native學習之路(12) - 用FlatList實現留言板評論功能 +(解決鍵盤跳出,頂出tabNavigator的問題)

(1) 知識點:

  • (1) concat():用于連接兩個或多個數組,返回一個新的數組。
   var item = [{
                            avatar1: "http://dummyimage.com/200x200/f2c779)",
                            date1: "1994-04-20",
                            key: "120000199" + i +"31207725X",
                            name1: "Cynthia Perez",
                            content1:this.state.content
                        }].concat(liuyanContent)   

                        i++;
// liuyanContent是get請求得到的數據,格式和上面的一樣,
// 只是 content內容不一樣,而且key要不一樣,這里用i++得到不同的key
  • (2) setState是異步的,所以要用回調函數立即取得新的狀態值后,要做什么。。
this.setState({
    _isSending:true
}, () => {
    回調,更新狀態后要做的事情
})
  • (2) FlatList的數據源格式:
<FlatList
  data={[{key: 'a'}, {key: 'b'}]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>
----------------------------
可以看到:在flatlist的data數據源中,是一個對象數組,即
[ 
{ key:'01', name:'woow.wu',avatar:'...'} , 
{ key:'02', name:'shengjudao',avatar:'...'}
]
---------------------------
可以看到:在renderItem中,帶有參數item,這里要打印item對象的數據結構
   _renderItemHuiFu(data) {
        // console.log(data)
        // liuyan = data
      return(
       <Text>{ data.item.name}</Text>
      )
  • (3) get請求,得到已評論的數據
 _getDataHuiFu() {
        fetch('http://rapapi.org/mockjs/22101/api/pinglun/huifu')
            .then( (response) => response.json() )
            .then( (data) => {
                // console.log(data)
                var Mock = MOCK.mock(data).huifulist;
                // console.log(Mock)
                // var mockDataArray = [];
                // mockDataArray = Mock.fuhuilist;
                // console.log(mockDataArray)
                this.setState({
                    huifu: Mock
                })

            } )
            .catch( (err)=> {
                console.error(err)
            })
    }
  • (3) post請求,提交留言的內容,返回seuccess布爾值,為true

  • (4) 提交按鈕和留言TextInput框

                    <View style={{margin:16,
                        borderWidth:1,
                        borderColor:'rgba(0,0,0,0.2)',
                        flexDirection:'row',
                        justifyContent:'space-between',
                        borderRadius:4,
                        alignItems:'center'
                    }}>
                        <TextInput
                            placeholder='請輸入評論內容'
                            underlineColorAndroid="transparent"
                            keybordType='numeric'
                            style={{height:80,width:width/2,fontSize:17}}
                            multiline={ true }
                            onChangeText={ (text) => {
                                this.setState({
                                    content: text
                                })
                            } }
                        >
                        </TextInput>

                        <TouchableHighlight onPress={ this._submit.bind(this) }>
                            <View style={{
                                width:100,
                                height:72,
                                backgroundColor:'#ff7454',
                                justifyContent:'center',
                                alignItems:"center",
                                borderRadius:4,
                            }}>
                                <Text style={{color:'white',fontSize:17,letterSpacing:20}}>提 交</Text>
                            </View>
                        </TouchableHighlight>
                    </View>
  • (5) 提交函數:
 _submit() {
        if(!this.state.content) {
            return alert('留言不能為空')
        }
        if( this.state._isSending){
            return alert('評論正在提交')
        }
        this.setState({
            _isSending:true
        },() => {
            fetch('http://rapapi.org/mockjs/22101/api/pinglun/huifupost',{
                method:'POST',
                headers: {
                    'Accept':'application/json',
                    'Content-Type':'application/json'
                },
                body:JSON.stringify({
                    'content':this.state.content
                })
            }).then( (response)=> response.json() )
                .then( (data) => {
                    if( data && data.success){
                        var liuyanContent = this.state.huifu;   //get請求得到的對象數組
                        // liuyanContent.map( (item) => {
                        //     ArrayHuiFu.push({
                        //         key: g,
                        //         data: item
                        //     })
                        //     g++;
                        // })
                        // console.log(ArrayHuiFu)
                        var item = [{
                            avatar1: "http://dummyimage.com/200x200/f2c779)",
                            date1: "1994-04-20",
                            key: "120000199" + i +"31207725X",
                            name1: "Cynthia Perez",
                            content1:this.state.content
                        }].concat(liuyanContent)

                        i++;

                        this.setState({
                            huifu:item,
                            _isSending: false
                        })

                    }
                })
        } )
    }

效果圖:


效果圖

效果圖

完整代碼:

/**
 * Created by WOOW.WU on 2017/8/1.
 */
/**
 * Created by WOOW.WU on 2017/8/1.
 */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Dimensions,
    ScrollView,
    Image,
    FlatList,
    TextInput,
    TouchableHighlight
} from 'react-native';

const { width, height } = Dimensions.get('window');
import Icon from'react-native-vector-icons/FontAwesome';
import MOCK from 'mockjs'
// pp2={
//     avatar:'http://dummyimage.com/600x300/f7d8d3)'
// }

var i=3;
var ArrayHuiFu = [];
// var liuyan = {};
export default class ff extends Component {
    constructor(props){
        super(props);
        this.state = {
            ping: {},
            huifu: [],
            content:'',
            _isSending: false
        }
    }

    componentDidMount() {
        this._getData()
        this._getDataHuiFu()
    }

    _getData() {
        fetch('http://rapapi.org/mockjs/22101/api/pinglun')
            .then( (response) => response.json() )
            .then( (data) => {
                var pp = MOCK.mock(data).pinglist;
                // var pp2 = MOCK.mock(data);
                // console.log(pp)
                // console.log(pp2)

                this.setState({
                    ping: pp,
                    // ping2: pp2
                })
            } )
            .catch( (err)=> {
                console.error(err)
            })
    }

    _getDataHuiFu() {
        fetch('http://rapapi.org/mockjs/22101/api/pinglun/huifu')
            .then( (response) => response.json() )
            .then( (data) => {
                // console.log(data)
                var Mock = MOCK.mock(data).huifulist;
                // console.log(Mock)
                // var mockDataArray = [];
                // mockDataArray = Mock.fuhuilist;
                // console.log(mockDataArray)
                this.setState({
                    huifu: Mock
                })

            } )
            .catch( (err)=> {
                console.error(err)
            })
    }


    _renderItemHuiFu(data) {
        // console.log(data)
        // liuyan = data
      return(
          <View style={{ padding:16,flexDirection:'row',justifyContent:'flex-start'}}>
              <View style={{ width:60,}}>
                  <Image source={{ uri: data.item.avatar1}} style={{ width:60,height:60,borderRadius:30}}></Image>
              </View>

              <View style={{paddingLeft:10}}>
                  <Text style={{fontSize: 18 }}>{data.item.name1}</Text>
                  <Text style={{ fontSize:18 ,lineHeight:30,width:width-102}}>{ data.item.content1 }</Text>
                  <Text>{ data.item.date1 }</Text>
              </View>


          </View>
      )
    }

    _submit() {
        if(!this.state.content) {
            return alert('留言不能為空')
        }
        if( this.state._isSending){
            return alert('評論正在提交')
        }
        this.setState({
            _isSending:true
        },() => {
            fetch('http://rapapi.org/mockjs/22101/api/pinglun/huifupost',{
                method:'POST',
                headers: {
                    'Accept':'application/json',
                    'Content-Type':'application/json'
                },
                body:JSON.stringify({
                    'content':this.state.content
                })
            }).then( (response)=> response.json() )
                .then( (data) => {
                    if( data && data.success){
                        var liuyanContent = this.state.huifu;
                        // liuyanContent.map( (item) => {
                        //     ArrayHuiFu.push({
                        //         key: g,
                        //         data: item
                        //     })
                        //     g++;
                        // })
                        // console.log(ArrayHuiFu)
                        var item = [{
                            avatar1: "http://dummyimage.com/200x200/f2c779)",
                            date1: "1994-04-20",
                            key: "120000199" + i +"31207725X",
                            name1: "Cynthia Perez",
                            content1:this.state.content
                        }].concat(liuyanContent)

                        i++;

                        this.setState({
                            huifu:item,
                            _isSending: false
                        })

                    }
                })
        } )
    }

    render() {
        // console.log(this.state.huifu)
        // console.log(pp2.avatar)
        // console.log(this.state.ping2)
        // console.log(this.state.ping2.pinglist)
        // console.log(this.state.ping2.pinglist)
        // console.log(this.state.ping2.pinglist.avatar1)

        return (
            <View style={styles.container}>
                <View style={ styles.myCircle } >
                    <Text style={ styles.myCircleText }>我的圈子</Text>
                    <Icon name="angle-right" size={ 30 } color="black"></Icon>
                </View>

                <ScrollView
                    automaticallAdjustContentInsert = { false }
                    style={ styles.ScrollView}
                >
                    <View style={ styles.infoBox }>
                        <View style={ styles.infoxBoxTop}>
                            <Image style={ styles.avatar } source={{ uri : this.state.ping.avatar1 }}></Image>
                            <Text style={ styles.name1}>{this.state.ping.name1}</Text>
                        </View>
                        <View style={styles.infoxContentContainer}>
                            <Text style={ styles.infoxContent }>{ this.state.ping.content1 }</Text>
                        </View>
                        <View>
                            <Text style={ styles.infoxDate }>{ this.state.ping.date1 }</Text>
                        </View>
                    </View>
                    <View style={{margin:16,
                        borderWidth:1,
                        borderColor:'rgba(0,0,0,0.2)',
                        flexDirection:'row',
                        justifyContent:'space-between',
                        borderRadius:4,
                        alignItems:'center'
                    }}>
                        <TextInput
                            placeholder='請輸入評論內容'
                            underlineColorAndroid="transparent"
                            keybordType='numeric'
                            style={{height:80,width:width/2,fontSize:17}}
                            multiline={ true }
                            onChangeText={ (text) => {
                                this.setState({
                                    content: text
                                })
                            } }
                        >
                        </TextInput>

                        <TouchableHighlight onPress={ this._submit.bind(this) }>
                            <View style={{
                                width:100,
                                height:72,
                                backgroundColor:'#ff7454',
                                justifyContent:'center',
                                alignItems:"center",
                                borderRadius:4,
                            }}>
                                <Text style={{color:'white',fontSize:17,letterSpacing:20}}>提 交</Text>
                            </View>
                        </TouchableHighlight>
                    </View>
                    <FlatList
                        data= { this.state.huifu }
                        renderItem = { this._renderItemHuiFu }
                    >
                    </FlatList>


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

const styles = StyleSheet.create({
    infoxContentContainer: {
        marginTop:10,
        marginBottom:10
    },
    infoxDate: {
        fontSize: 16
    },
    infoxContent: {
        fontSize: 18,
        lineHeight:36
    },
    name1: {
        fontSize: 20
    },
    infoBox: {
        padding:16,
        borderBottomColor: 'rgba(0,0,0,0.1)'
    },
    infoxBoxTop: {
        flexDirection:'row',
        justifyContent:'flex-start',
        alignItems:'center'
    },
    avatar: {
        width:100,
        height:100,
        borderRadius:50,
        marginRight: 10
    },
    myCircleText: {
        fontSize: 18
    },
    myCircle: {
        height: 60,
        width: width,
        backgroundColor: 'rgba(0,0,0,0.1)',
        flexDirection: 'row',
        justifyContent:'space-between',
        alignItems:'center',
        paddingLeft: 20,
        paddingRight: 20
    },
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
});

(2) 鍵盤跳出,頂出tabnavigator

(詳細)http://www.lxweimin.com/p/b877115fff1b
http://blog.csdn.net/u011690583/article/details/53808773

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容