首页 > 解决方案 > 如果条件为真,如何添加新组件?反应原生

问题描述

我是 react-native 的新手,我做了一个简单的块状注释,现在的问题是我想显示用户进入应用程序后已经保存的注释,因为我使用以下代码:

show_notes = async() => {
    try {
        const data = await AsyncStorage.getItem("array_notes");
        if (data != null) {
            const array_notes = JSON.parse(data);
            <Notes title = {array_notes[0].title} content = {array_notes[0].content}></Notes>
        }else {
            console.log("with no data");
        }
    }catch (error) {
        console.log(error);
    }
}

注意它是一个保存在另一个文件夹中的组件,所以我必须导入它才能使用它,下面是它的代码:

function Notes(props) {
    return (
        <View style = {props.style}>
            <Text>{props.title}</Text>
            <Text>{props.content}</Text>
        </View>
    );
}
export default Notes;

这是完整的代码:

class Create_note extends Component {
    constructor() {
        super();
        this.state = {
            title: "",
            content: "",
            text: "",
        }
        this.show_notes();
    }

    save_Data = async() => {
        try {
            const array_notes = await AsyncStorage.getItem("array_notes");
            if (array_notes === null) {
                const array_notes = [];
                await AsyncStorage.setItem("array_notes", JSON.stringify(array_notes));
            }else {
                const new_note = {'title': this.state.title, 'content': this.state.content};
                const array_notes = await AsyncStorage.getItem("array_notes");
                array_notes.push(new_note);
                await AsyncStorage.setItem("array_notes", JSON.stringify(array_notes));
            }
        }catch(error) {
            console.log(error);
        }
    }

    see_saved_Data = async() => {
        try {
            const data = await AsyncStorage.getItem("array_notes");
            if (data != null) {
                const array_notes = JSON.parse(data);
            }else {
                console.log("no array");
            }
        }catch(error) {
            console.log(error);
        }
    }
    
    show_notes = async() => {
        try {
            const data = await AsyncStorage.getItem("array_notes");
            if (data != null) {
                const array_notes = JSON.parse(data);
                <Notes title = {array_notes[0].title} content = {array_notes[0].content}></Notes>
            }else {
                console.log("with no data");
            }
        }catch (error) {
            console.log(error);
        }
    }

    render() {
        return  (
            <>
            <Text style = {this.styles.Text }>Welcome to Shum Note!</Text>
            <View>
                <TextInput style = {this.styles.TextInput_title} placeholder = "Title" multiline = {true} maxLength = {80} onChangeText = {(title) => this.setState({title: title})}></TextInput>
                <TextInput style = {this.styles.TextInput_content} placeholder = "Content" multiline = {true} onChangeText = {(content) => this.setState({content: content})}></TextInput>
                <Button title = "Save" onPress = {this.save_Data}></Button>
                <Button title = "See saved notes" onPress = {this.see_saved_Data}></Button>
            </View>
            <View style = {this.styles.back_Button}>
                <Button title = "Go back home" onPress = {() => this.props.navigation.navigate("Home")}></Button>
            </View>
            </>    
        );
    }

我想知道它如何动态添加组件?所以我不需要编写太多代码并将代码分成小块

标签: javascriptreact-native

解决方案


您可以使用 FlatList,在获取保存的笔记后,将它们添加到状态,然后在平面列表中呈现项目,查看此示例:

import React, {Component} from 'react';
import{AsyncStorage, View, ScrollView, FlatList} from 'react-native';
import {Text, List} from 'native-base';

class Notes extends Component {

  constructor(props) {

    super(props);

    this.state = {
      notes_array: []
    }

  }

  componentDidMount () {
    this.fetchNotes();
  }
  render () {

    return (
        <ScrollView>
        <View style={{margin: 5, marginTop: 5}}>     
        <List>
            <FlatList
                data={this.state.notes_array}
                renderItem={({item, index}) =>
                <View style={{flex: 1}}>
                        <Text>{item.title}</Text>
                        <Text>{item.content}</Text>
                </View>        
                }
                keyExtractor={(item, index) => index.toString()}
            />
        </List>

        </View> 
        </ScrollView>
    )
  }


async fetchNotes () {

      let notesJSON= await AsyncStorage.getItem('notes_array');
      let notes = JSON.parse(notesJSON);
      const notesArray = notes || [];
      this.setState({
        notes_array: notesArray
      });
  }

}

export default Notes;

推荐阅读