javascript - 处理 expo react native 中的多个复选框

标签 javascript reactjs react-native checkbox expo

我希望能够在我的 expo React native 应用程序中添加多个复选框。我在下面提供相关代码。我的类中有一个数组,其中包含有关复选框的详细信息,它有一个 ID、必须放在旁边的文本以及检查复选框是否被选中的检查。


我的代码


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
            inputTxt: "",
            checks: [
                {id: 1, txt: "first check", isChecked: false },
                {id: 2, txt: "second check", isChecked: false }
            ]
        };
    }
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.text}>Details Screen</Text>
                <View>
                    <View style={styles.checkboxContainer}>
                        <CheckBox/>
                         {/* Add all the checkboxes from my this.state.checks array here */}
                        <Text style={styles.label}>Do you like React Native?</Text>
                    </View>
                </View>
              [...]
            </View>
        );
    }
}

最佳答案

这里是您可以非常轻松地实现它的方法。

我在这里使用了功能组件而不是基于类的组件,但底层逻辑保持不变:

最终输出:

enter image description here

示例 1:完整源代码(使用功能组件和 Hook ):

import React, { useState, useEffect } from 'react';
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  CheckBox,
  Button,
  Modal,
} from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

const data = [
  { id: 1, txt: 'first check', isChecked: false },
  { id: 2, txt: 'second check', isChecked: false },
  { id: 3, txt: 'third check', isChecked: false },
  { id: 4, txt: 'fourth check', isChecked: false },
  { id: 5, txt: 'fifth check', isChecked: false },
  { id: 6, txt: 'sixth check', isChecked: false },
  { id: 7, txt: 'seventh check', isChecked: false },
];

export default App = () => {
  const [products, setProducts] = useState(data);

  const handleChange = (id) => {
    let temp = products.map((product) => {
      if (id === product.id) {
        return { ...product, isChecked: !product.isChecked };
      }
      return product;
    });
    setProducts(temp);
  };

  let selected = products.filter((product) => product.isChecked);

  const renderFlatList = (renderData) => {
    return (
      <FlatList
        data={renderData}
        renderItem={({ item }) => (
          <Card style={{ margin: 5 }}>
            <View style={styles.card}>
              <View
                style={{
                  flexDirection: 'row',
                  flex: 1,
                  justifyContent: 'space-between',
                }}>
                <CheckBox
                  value={item.isChecked}
                  onChange={() => {
                    handleChange(item.id);
                  }}
                />
                <Text>{item.txt}</Text>
              </View>
            </View>
          </Card>
        )}
      />
    );
  };

  return (
    <View style={styles.container}>
      <View style={{ flex: 1 }}>{renderFlatList(products)}</View>
      <Text style={styles.text}>Selected </Text>
      <View style={{ flex: 1 }}>{renderFlatList(selected)}</View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

  card: {
    padding: 10,
    margin: 5,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  modalView: {
    margin: 20,
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 5,
    justifyContent: 'space-between',
    alignItems: 'center',
    elevation: 5,
  },
  text: {
    textAlign: 'center',
    fontWeight: 'bold',
  },
});

您可以在此处使用已完成的工作代码:Expo Snack

示例 2:完整源代码(使用基于类的组件):

import React, { useState, useEffect, Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  CheckBox,
  Button,
  Modal,
} from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

const data = [
  { id: 1, txt: 'first check', isChecked: false },
  { id: 2, txt: 'second check', isChecked: false },
  { id: 3, txt: 'third check', isChecked: false },
  { id: 4, txt: 'fourth check', isChecked: false },
  { id: 5, txt: 'fifth check', isChecked: false },
  { id: 6, txt: 'sixth check', isChecked: false },
  { id: 7, txt: 'seventh check', isChecked: false },
];

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: data,
    };
  }

  handleChange = (id) => {
    let temp = this.state.products.map((product) => {
      if (id === product.id) {
        return { ...product, isChecked: !product.isChecked };
      }
      return product;
    });
    this.setState({
      products: temp,
    });
  };

  renderFlatList = (renderData) => {
    return (
      <FlatList
        data={renderData}
        renderItem={({ item }) => (
          <Card style={{ margin: 5 }}>
            <View style={styles.card}>
              <View
                style={{
                  flexDirection: 'row',
                  flex: 1,
                  justifyContent: 'space-between',
                }}>
                <CheckBox
                  value={item.isChecked}
                  onChange={() => {
                    this.handleChange(item.id);
                  }}
                />
                <Text>{item.txt}</Text>
              </View>
            </View>
          </Card>
        )}
      />
    );
  };

  render() {
    let selected = this.state.products?.filter((product) => product.isChecked);
    return (
      <View style={styles.container}>
        <View style={{ flex: 1 }}>
          {this.renderFlatList(this.state.products)}
        </View>
        <Text style={styles.text}>Selected </Text>
        <View style={{ flex: 1 }}>{this.renderFlatList(selected)}</View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

  card: {
    padding: 10,
    margin: 5,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  modalView: {
    margin: 20,
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 5,
    justifyContent: 'space-between',
    alignItems: 'center',
    elevation: 5,
  },
  text: {
    textAlign: 'center',
    fontWeight: 'bold',
  },
});

您可以在此处使用已完成的工作代码:Expo Snack

关于javascript - 处理 expo react native 中的多个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65205428/

相关文章:

javascript - 找不到 Typescript 自己的模块

react-native-router-flux:如何防止在选项卡之间切换时重置选项卡场景历史堆栈?

javascript - 当有 React Native 输入附件时如何滚动到焦点上的文本输入

javascript - 为什么我的 for 循环在 5 次迭代后停止? (在函数 hello() 中)

javascript - 在 JavaScript 函数中使用 AJAX 调用的结果

javascript - 如何删除第 3 个之后的每个 {element}?

javascript - Babel 加载器无法导入 React

reactjs - redux-form 字段值可以保存对象而不仅仅是字符串吗?

javascript - react Material 重置表格值

react-native - TextInput 不需要的下划线