我想从表格中收集所有数据
我正在使用反应钩子。从对钩子的理解来看,我只需要使用一个集合来更新变量。目前这不适用于我。
我想收集所有信息,然后在onSubmit表单中进行控制台记录。下一步
我也使用工作代码创建了一个code sandbox
任何解释都值得赞赏
const SearchBar = () => {
const [searchData, setSearchData] = useState({
startDate: "",
endDate: "",
inputField: "",
platformToSearch: ""
});
const { handleSubmit, register, reset, control } = useForm({ defaultValues });
const [selectedStartDate, setSelectedStartDate] = useState(
new Date("2014-08-18T21:11:54")
);
const [selectedEndDate, setSelectedEndDate] = useState(
new Date("2014-20-18T21:11:54")
);
/*dropdown for social platforms*/
const [query, setQuery] = useState([]);
const [expanded, setExpanded] = useState(false);
// const myRef = useRef(null);
const showPlatformOptions = () => {
if (!expanded) {
setExpanded(true);
} else {
setExpanded(false);
}
};
const handlePlatformQueryChange = event => {
if (event.target.checked && !query.includes(event.target.value)) {
setQuery([...query, event.target.value]);
} else if (!event.target.checked && query.includes(event.target.value)) {
setQuery(query.filter(q => q !== event.target.value));
}
setSearchData({ ...searchData.platformToSearch, query });
};
const handleStartDateChange = date => {
//console.log("Selected start date:", date._d)
// useEffect(() => {
// setSearchData(...searchData.startDate, date._d);
// }, [searchData]);
setSearchData(...searchData.startDate, date._d);
setSelectedStartDate(date._d);
};
const handleEndDateChange = date => {
//console.log("Selected end date:", date)
setSearchData(...searchData.endDate, date._d);
setSelectedEndDate(date._d);
};
const onSubmit = data => {
// How should this be
//updated to store all the slected items from the form
console.log("Collected Data:", searchData);
console.log("searchData:", searchData);
alert(JSON.stringify(data, null, 2));
reset(defaultValues);
};
return (
<div>
<form onSubmit={handleSubmit(data => onSubmit(data))}>
<div className="flex">
<SelectSocialPlatform
query={query}
expanded={expanded}
onClick={showPlatformOptions}
onChange={handlePlatformQueryChange}
/>
<Calendar
name="StartDate"
label="START DATE"
value={selectedStartDate}
onChange={handleStartDateChange}
/>
<Calendar
name="EndDate"
label="END DATE"
value={selectedEndDate}
onChange={handleEndDateChange}
/>
<InputField
name="inputField"
placeholder="Search by keywords, #hashtags, or @socialmediahandles"
refs={register}
className="border-blue-200 border rounded w-full h-20 py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
/>
<SearchButton
className="bg-blue-800 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded h-20 w-40"
text="Search"
onClick={handleSubmit(onSubmit)}
type="submit"
/>
</div>
</form>
</div>
);
};
export default SearchBar;