如何动态添加更多组件React Native

时间:2017-08-03 07:28:14

标签: reactjs react-native react-native-android react-native-ios react-native-0.46

我想在点击按钮后添加更多组件。你可以分享代码或想法,以便我可以实现吗?如图所示,每次用户点击添加按钮时,都会添加一行/组件。

2 个答案:

答案 0 :(得分:11)

这是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. 进行更新
  4. render()被触发。
  5. 更多<MyComponent>已添加到“查看并显示”
  6. =====

    2017/8/3编辑:

    如果您想进一步删除<MyComponent>,则应该处理道具keykey充当反应框架的变化检测器,自动增量键适合您的情况。例如:

    _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>
        );
    }
    

答案 1 :(得分:1)

我认为您可能要问的是要在todo应用中添加任务。 我的回答如下。 一开始,有一个数组作为 data ,其中三个项存储在组件状态中,而这三个项则显示在屏幕上。然后,我使用模式从用户那里获取输入,并将该输入存储为 newInput 在组件状态下。然后,我使用按钮将 newInput 添加到 handleModalClick 函数的数据中。然后,将 newInput 值添加到 data 数组中。 data 数组中的所有元素都显示在屏幕上。

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;