簡體   English   中英

如何動態添加更多組件 React Native

[英]How To Add More component dynamically React Native

單擊按鈕后,我想添加更多組件。 您可以分享代碼或想法以便我可以實施嗎? 如圖所示,每次用戶單擊添加按鈕時,都會添加一行/組件。

state閃耀的地方,

例如:

constructor(props) {
   super(props);

   this._handleAddButton = this._handleAddButton.bind(this);

   this.state = {    /* initial your state. without any added component */
      data: []
   }
}

_handleAddButton() {
    let newly_added_data = { title: 'new title', content: 'new content goes here' };

    this.setState({
        data: [...this.state.data, newly_added_data]
    });
}

render() {
    let added_buttons_goes_here = this.state.data.map( (data, index) => {
        return (
            <MyComponent key={index} pass_in_data={data} />
        )
    });

    return (
        <View>
            <Button title="Add more" onPress={this._handleAddButton} />
            {added_buttons_goes_here}
        </View>
    );
}

所以每次你點擊按鈕時,

  1. _handleAddButton 被調用
  2. 添加了新數據,使用setState()更新
  3. render()被觸發。
  4. 更多<MyComponent>添加到視圖和顯示

================

2017/8/3 編輯:

如果您想進一步刪除<MyComponent> ,則應注意 prop key key充當反應框架的更改檢測器,自動增量鍵適合您的情況。 例子:

_handleAddButton() {
    let newly_added_data = {
        /* psedo code to simulate key auto increment */
        key: this.state.data[this.state.data.length-1].key+1,
        title: 'new title',
        content: 'new content goes here'
    };

    this.setState({
        data: [...this.state.data, newly_added_data]
    });
}

_handleRemoveButton(key) {
    let result = this.state.data.filter( (data) => data.key !== key );

    this.setState({
        data: result,
    });
}

render() {
    let added_buttons_goes_here = this.state.data.map( (data, index) => {
        return (
            <MyComponent key={data.key} pass_in_data={data}>
                /// psedo code of pass-in remove button as a children
                <Button title="Remove" onPress={ () => this._handleRemoveButton(data.key) } />
            </MyComponent>
        )
    });

    return (
        <View>
            <Button title="Add more" onPress={this._handleAddButton} />
            {added_buttons_goes_here}
        </View>
    );
}

我想你可能會問在 todo 應用程序中添加任務。 我的回答如下。 一開始,有一個數組作為數據,其中包含三個項目,因為我存儲在組件的狀態中,並且這 3 個項目顯示在屏幕上。 然后我使用模態從用戶那里獲取輸入並將該輸入存儲為組件狀態中的newInput 然后我使用一個按鈕將該newInput添加到handleModalClick函數中的數據中。 然后將newInput值添加到數據數組中。 數據數組中的所有元素都顯示在屏幕上。

 import React, { Component } from "react"; import { SafeAreaView, View, FlatList, StyleSheet, Text, TextInput, Button, Modal, TouchableHighlight, Alert, TouchableOpacity } from "react-native"; import Constants from "expo-constants"; import uuid from "uuid/v1"; import { Ionicons } from "@expo/vector-icons"; export class Test extends Component { constructor(props) { super(props); this.state = { data: [ { id: 1, title: "First Item" }, { id: 2, title: "Second Item" }, { id: 3, title: "Third Item" } ], modalVisible: false, newInput: "" }; } setModalVisible(visible) { this.setState({ modalVisible: visible }); } handleModalClick = () => { this.setState( { data: [...this.state.data, { id: uuid(), title: this.state.newInput }] }, this.setState({ newInput: "" }) ); }; render() { return ( <SafeAreaView style={styles.container}> <FlatList data={this.state.data} renderItem={({ item }) => ( <View style={styles.item}> <Text style={styles.title}>{item.title}</Text> </View> )} keyExtractor={item => item.id} /> <View style={{ marginTop: 22 }}> <Modal animationType="slide" transparent={false} visible={this.state.modalVisible} onRequestClose={() => { Alert.alert("Modal has been closed."); }} > <View style={{ marginTop: 22 }}> <View> <TextInput placeholder="ENTER" onChangeText={text => { this.setState({ newInput: text }); }} value={this.state.newInput} /> <Button title="click" onPress={this.handleModalClick} /> <TouchableHighlight onPress={() => { this.setModalVisible(!this.state.modalVisible); }} > <Ionicons name="md-close-circle" size={50} color="red" /> </TouchableHighlight> </View> </View> </Modal> <TouchableOpacity onPress={() => { this.setModalVisible(true); }} > <Ionicons name="md-add-circle" size={100} color="violet" /> </TouchableOpacity> </View> </SafeAreaView> ); } } const styles = StyleSheet.create({ container: { flex: 1, marginTop: Constants.statusBarHeight }, item: { backgroundColor: "#f9c2ff", padding: 10, marginVertical: 8, marginHorizontal: 16 }, title: { fontSize: 18 }, input: { borderWidth: 2 } }); export default Test;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM