使用 react-hook-form 反应原生形式

时间:2021-05-18 20:18:51

标签: react-native radio-button native-base react-hook-form

我正在开发一个 React Native 项目,我正在尝试使用 react-hook-form 库注册一个带有单选按钮的表单。但是 useForm() 的 defaultValues 对象没有考虑 radio 值的状态更新 但是我 console.log 状态和更新工作 完整代码如下:

import React, { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Radio } from "native-base";

const myForm = () => {
  //Create an array of all items
  const itemsTab = [
    {
      label: "item 1",
      value: "1",
    },
    {
      label: "item 2",
      value: "2",
    },
    {
      label: "item 3",
      value: "3",
    },
  ];

  const [itemChecked, setItemChecked] = useState("");

  const { handleSubmit, control, reset } = useForm({
    defaultValues: { itemValue: itemChecked },
  });
  const submitForm = values => {
    console.log(values);
  };
  console.log(`ok: ${itemChecked}`);

  return (
    <View>
      {/* title */}
      <Text>list of items</Text>
      {/* radio buttons */}
      {itemsTab.map((item, index) => {
        const { label } = item;
        return (
          <View key={index}>
            <TouchableOpacity onPress={() => setItemChecked(value)}>
              <View style={styles.radioBox}>
                <Controller
                  name="itemValue"
                  control={control}
                  as={
                    <Radio
                      //   name="itemValue"
                      selected={itemChecked === item.value}
                      color="rgba(0,0,0,.5)"
                      selectedColor=red
                    />
                  }
                />
                <Text>{label}</Text>
              </View>
            </TouchableOpacity>
            {/* submit button */}
            <TouchableOpacity
              onPress={handleSubmit(submitForm)}
            >
              <Text>
                submit
              </Text>
            </TouchableOpacity>
          </View>
        );
      })}
    </View>
  );
};

0 个答案:

没有答案