You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native实现三输入框值求和并将结果存入数组展示方案

Solution for Summing Three TextInput Values and Storing Results in an Array (React Native)

Hey there! Let's build this feature step by step. We'll use React Hooks (useState) to manage our state, handle input changes, compute the sum, and display the history of results.

Step 1: Set Up State Variables

We need state to track:

  • The input values of the three TextInput fields
  • The array that stores all past sum results
import React, { useState } from 'react';
import { View, TextInput, Button, Text, FlatList, StyleSheet } from 'react-native';

export default function SumCalculator() {
  // Track each input value
  const [num1, setNum1] = useState('');
  const [num2, setNum2] = useState('');
  const [num3, setNum3] = useState('');
  // Track the array of sum results
  const [sumHistory, setSumHistory] = useState([]);

Step 2: Handle Input Changes

Create handler functions to update the state whenever the user types in a TextInput. We'll add a simple regex check to ensure only numeric values (including decimals) are allowed.

const handleNum1Change = (text) => {
    // Allow only numeric input to avoid invalid values
    if (/^\d*\.?\d*$/.test(text)) {
      setNum1(text);
    }
  };

  const handleNum2Change = (text) => {
    if (/^\d*\.?\d*$/.test(text)) {
      setNum2(text);
    }
  };

  const handleNum3Change = (text) => {
    if (/^\d*\.?\d*$/.test(text)) {
      setNum3(text);
    }
  };

Step 3: Compute Sum and Update History

Create a function that calculates the sum of the three numbers, then adds the result to the sumHistory array. We'll handle empty inputs by treating them as 0 to avoid NaN errors.

const calculateSum = () => {
    // Convert inputs to numbers, default to 0 if empty
    const number1 = num1 ? parseFloat(num1) : 0;
    const number2 = num2 ? parseFloat(num2) : 0;
    const number3 = num3 ? parseFloat(num3) : 0;

    const total = number1 + number2 + number3;

    // Prepend the new sum to the history (shows latest first; use [...prevHistory, total] to append)
    setSumHistory(prevHistory => [total, ...prevHistory]);

    // Optional: Clear input fields after calculation for better UX
    setNum1('');
    setNum2('');
    setNum3('');
  };

Step 4: Display the Sum History

Use a FlatList (efficient for longer lists) to render all past sum results. We'll also add a fallback message when there are no results yet.

// Render each sum item in the history
  const renderSumItem = ({ item }) => (
    <View style={styles.historyItem}>
      <Text style={styles.historyText}>Sum Result: {item.toFixed(2)}</Text>
    </View>
  );

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Three Number Sum Calculator</Text>

      {/* Input Fields */}
      <TextInput
        style={styles.input}
        placeholder="Enter number 1"
        keyboardType="numeric"
        value={num1}
        onChangeText={handleNum1Change}
      />
      <TextInput
        style={styles.input}
        placeholder="Enter number 2"
        keyboardType="numeric"
        value={num2}
        onChangeText={handleNum2Change}
      />
      <TextInput
        style={styles.input}
        placeholder="Enter number 3"
        keyboardType="numeric"
        value={num3}
        onChangeText={handleNum3Change}
      />

      {/* Calculate Button */}
      <Button title="Calculate Sum" onPress={calculateSum} />

      {/* Sum History */}
      <Text style={styles.historyTitle}>Sum History:</Text>
      {sumHistory.length === 0 ? (
        <Text style={styles.emptyText}>No sums calculated yet.</Text>
      ) : (
        <FlatList
          data={sumHistory}
          renderItem={renderSumItem}
          keyExtractor={(item, index) => index.toString()}
          style={styles.historyList}
        />
      )}
    </View>
  );
}

Step 5: Add Basic Styling

Let's add some styles to make the component look clean and user-friendly:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    marginTop: 50,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
  },
  input: {
    height: 40,
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 5,
    paddingHorizontal: 10,
    marginBottom: 15,
  },
  historyTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginTop: 25,
    marginBottom: 10,
  },
  historyList: {
    flex: 1,
  },
  historyItem: {
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  historyText: {
    fontSize: 16,
  },
  emptyText: {
    fontSize: 14,
    color: '#666',
    fontStyle: 'italic',
  },
});

Quick Notes

  • The regex input validation ensures users can't enter non-numeric characters, preventing calculation errors.
  • We use toFixed(2) in the history display to keep decimal results consistent (adjust the number if you need more/less precision).
  • FlatList is preferred over a simple map for rendering the history because it's optimized for performance with long lists.

内容的提问来源于stack exchange,提问作者Nazeer c s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:20:38