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

React Native实现带单选按钮的职位列表并获取选中值时遭遇‘input must be a function received undefined’错误的解决问询

Hey there! Let's break down what's going wrong and fix this step by step.

First, the main issue causing that error is you're using a web HTML <input> tag in React Native—React Native doesn't understand web HTML elements like this. Instead, you need to use React Native-specific components for radio buttons.

Second, your event handling logic is built for web (using e.target.value), which doesn't work in React Native because event objects here are different. Also, your state management for both the switches and radio buttons needs some tweaks to work correctly.

Let's fix this with a complete solution:

Step 1: Use a React Native Radio Button Component

React Native doesn't have a built-in radio button, so we'll use the community-maintained @react-native-community/radio-button package (or you can build a custom one if you prefer). First install it:

npm install @react-native-community/radio-button
# or yarn add @react-native-community/radio-button

Step 2: Updated Code with Fixes

Here's the corrected code that addresses all issues:

import React, { useState } from 'react';
import { View, Text, Switch, StyleSheet } from 'react-native';
import RadioButton from '@react-native-community/radio-button';

export default function Home({ navigation }) {
  // Note: If you're using React Navigation 5+, use `route.params` instead of `getParam`
  const roles = navigation.getParam('roles');
  
  // Track switch state for each individual role (instead of a single shared state)
  const [switchStates, setSwitchStates] = useState({});
  // Track the currently selected role for radio buttons
  const [selectedRole, setSelectedRole] = useState(() => {
    // Initialize with role id=3 if it exists
    const initialKey = Object.keys(roles).find(key => roles[key].id === 3);
    return initialKey ? roles[initialKey].name : null;
  });

  // Toggle switch for a specific role
  const toggleSwitch = (roleName) => {
    setSwitchStates(prev => ({
      ...prev,
      [roleName]: !prev[roleName]
    }));
  };

  // Handle radio button selection
  const handleRadioSelect = (roleName) => {
    setSelectedRole(roleName);
    alert(`Selected Role: ${roleName}`);
  };

  return (
    <View style={styles.container}>
      {Object.keys(roles).map((key) => {
        const role = roles[key];
        return (
          <View key={key} style={styles.itemRow}>
            <Text style={styles.roleName}>{role.name}</Text>
            <Switch
              trackColor={{ false: "#767577", true: "#81b0ff" }}
              thumbColor={switchStates[role.name] ? "#f5dd4b" : "#f4f3f4"}
              ios_backgroundColor="#3e3e3e"
              onValueChange={() => toggleSwitch(role.name)}
              value={switchStates[role.name] || false}
            />
            <RadioButton
              value={role.name}
              selected={selectedRole === role.name}
              onPress={() => handleRadioSelect(role.name)}
            />
          </View>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  itemRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  roleName: {
    fontSize: 16,
    flex: 1,
  },
});

Key Fixes Explained:

  1. Replaced <input> with React Native RadioButton: We're using a proper native component instead of web HTML, which eliminates the "input must be a function" error.
  2. Per-Role Switch State: Instead of a single isEnabled state for all switches, we use an object switchStates to track each role's switch status—so toggling one switch doesn't affect others.
  3. Controlled Radio Buttons: The selectedRole state tracks which radio button is active, and we bind this to the selected prop of each RadioButton. This ensures the UI stays in sync with your state.
  4. Simplified Event Handling: We pass the role name directly to the handler functions instead of relying on web-style event objects, which is how React Native expects event handling to work.

Alternative: Custom Radio Button (No Third-Party Package)

If you don't want to use a community package, you can build a simple custom radio button component:

import { TouchableOpacity, View } from 'react-native';

const CustomRadioButton = ({ selected, onPress, label }) => {
  return (
    <TouchableOpacity onPress={onPress} style={{ flexDirection: 'row', alignItems: 'center' }}>
      <View style={{
        width: 20,
        height: 20,
        borderRadius: 10,
        borderWidth: 2,
        borderColor: selected ? '#81b0ff' : '#767577',
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 8,
      }}>
        {selected && (
          <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: '#81b0ff' }} />
        )}
      </View>
      <Text>{label}</Text>
    </TouchableOpacity>
  );
};

Then replace the RadioButton import and usage with this custom component—it works the same way!

内容的提问来源于stack exchange,提问作者user11710915

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:53:12