csv-react & react-hook-form



大家晚上好,我被这段代码困了好几个小时,我不知道怎么弄清楚。我想从表单中检索数据,将其转换为CSV文件或Excel表。我使用了第三方库,比如CSV-react和react-hook-form。如果你能帮助我,我会很感激的,谢谢。

import React from "react";
import { useForm } from "react-hook-form";
import { CSVLink } from "react-csv";

export default function App() {
const { register, handleSubmit } = useForm();
const headers = [
{ label: "Address", key: "address" },
{ label: "T-Shirt Size", key: "size" },
{ label: "mail", key: "mail" },
];
let data = [];

const onSubmit = data => {
console.log(data);
};


return (  
<form onSubmit={handleSubmit(onSubmit)}>
<label>Address</label>
<input {...register("address")} />
<label>T-Shirt Size</label>
<select {...register("size")}>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<label>mail</label>
<input {...register("mail")} />
<label>       
<input type="checkbox" required / >
Agreement to the Data Privacy Policy</label>

<CSVLink data={data} headers={headers}>
Download me
</CSVLink>;
<input type="submit" />
</form>
);
}

所以,我在一个论坛上找到了一个解决方案,我想和大家分享一下。

import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { CSVLink } from "react-csv";

export default function App() {
const { register, handleSubmit } = useForm();
const [csvData, setCsvData] = useState([])
const headers = [
{ label: "Address", key: "address" },
{ label: "T-Shirt Size", key: "size" },
{ label: "mail", key: "mail" },
];

const onSubmit = data => {
//console.log(data);
setCsvData(prev => [...prev, data])
};


return (  
<form onSubmit={handleSubmit(onSubmit)}>
<label>Address</label>
<input {...register("address")} />
<label>T-Shirt Size</label>
<select {...register("size")}>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<label>mail</label>
<input {...register("mail")} />
<label>       
<input type="checkbox" required / >
Agreement to the Data Privacy Policy</label>

<CSVLink data={csvData} headers={headers}>
Download me
</CSVLink>;
<input type="submit" />
</form>
);
}

最新更新