首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用React-Hook-Form插入

使用React-Hook-Form插入
EN

Stack Overflow用户
提问于 2021-02-17 05:30:18
回答 1查看 260关注 0票数 0

我有一个带有React-Hook-Form的模式,它将数据发送到我的MySql数据库中,但是当我点击按钮时,只有4列被填充(‘id’,createdAt,updatedAt和user_id),而我有更多的3列(‘title’,'description','photo')。

代码语言:javascript
复制
export default function FeedModal() {
const [form, setForm] = useState([]);
const { register, handleSubmit, setValue } = useForm();
const [isModalVisible, setModalVisible] = useState(false);

useEffect(() => {
    register({ title: 'title' });
    register({ description: 'description' })
}, [register]);

const onSubmit = async ({ title, description, photo }) => {
    const data = { title, description, photo };
    await api.post('/posts/1/create')
        .then(response => setForm(response(data)))
        .then(JSON.stringify(form))
        .catch(console.error());
    return () => handleSubmit(onSubmit);
}

const toogleModal = () => {
    setModalVisible(!isModalVisible);
}

我的表单:

代码语言:javascript
复制
            <View style={styles.Card}>
                <View style={styles.pubCard}>
                    <Text style={styles.intro}>Criar publicação</Text>
                    <TextInput
                        value={form.title}
                        name={'title'}
                        ref={register({ required: true })}
                        onChangeText={text => setValue("title", text, { shouldValidate: true })}
                        multiline={true}
                        style={styles.titleInput}
                        placeholder="Titulo">
                    </TextInput>
                </View>

                <View style={styles.btnView}>
                    <TouchableOpacity style={styles.upload} title="Selecionar Foto" >
                        <Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular', textAlign: 'center' }}>Selecionar Foto</Text>
                    </TouchableOpacity>
                </View>

                <KeyboardAvoidingView style={styles.descView}>
                    <TextInput
                        value={form.description}
                        name={"description"}
                        ref={register({ required: true })}
                        onChangeText={text => setValue("description", text)}
                        multiline={true}
                        style={styles.descInput}
                        placeholder="Nos descreva com detalhes sobre o caso do seu Pet"></TextInput>
                </KeyboardAvoidingView>
                <View style={styles.buttons}>
                    <TouchableOpacity onPress={toogleModal} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}>Fechar</Text></TouchableOpacity>
                    <TouchableOpacity onPress={handleSubmit(onSubmit)} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}> Criar</Text></TouchableOpacity>
                </View>
            </View>
EN

回答 1

Stack Overflow用户

发布于 2021-02-22 10:26:12

也许在这里使用useFieldArray会更好,因为您正在谈论插入。

https://react-hook-form.com/api#useFieldArray

然后,您可以使用insert操作。例如:

代码语言:javascript
复制
import React from "react";
import { useForm, useFieldArray } from "react-hook-form";

function App() {
  const { register, control, handleSubmit, reset, trigger, setError } = useForm({
    // defaultValues: {}; you can populate the fields by this attribute 
  });
  const { fields, append, prepend, remove, swap, move, insert } = useFieldArray({
    control,
    name: "test"
  });
  
  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <ul>
        {fields.map((item, index) => (
          <li key={item.id}>
            <input
              name={`test[${index}].firstName`}
              ref={register()}
              defaultValue={item.firstName} // make sure to set up defaultValue
            />
            <Controller
              as={<input />}
              name={`test[${index}].lastName`}
              control={control}
              defaultValue={item.lastName} // make sure to set up defaultValue
            />
            <button type="button" onClick={() => remove(index)}>Delete</button>
          </li>
        ))}
      </ul>
      <button
        type="button"
        onClick={() => insert(1, { firstName: "appendBill", lastName: "appendLuo" })}
      >
        append
      </button>
      <input type="submit" />
    </form>
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66232457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档