【发布时间】:2019-09-08 15:41:20
【问题描述】:
我正在尝试学习 React 和 React Hooks。我创建了位于另一个文件中的自定义钩子:CustomHook.ts。我在我的ContactForm.tsx 中使用它。我遇到的问题是在<input /> 标签中的每个value={inputs.property} 内。 Typescript 无法解析每个inputs._propertyName 的类型。
我已经定义了一个接口IContact,它定义了我想要使用的类型。我目前没有使用这个界面,因为我不知道把它放在哪里。
任何帮助将不胜感激!
错误:
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(35,31)
TS2339: Property 'subject' does not exist on type '{}'.
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(46,31)
TS2339: Property 'email' does not exist on type '{}'.
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(57,31)
TS2339: Property 'name' does not exist on type '{}'.
ERROR in /jefthimi/src/components/Contact/ContactForm.tsx(68,31)
TS2339: Property 'comments' does not exist on type '{}'.
ContactForm.tsx
import React from 'react';
import './ContactForm.scss';
import useContactForm from './CustomHook';
interface IContact {
subject: string;
email: string;
name: string;
comments: string;
}
const message = (inputs: any) => {
alert(`Message Sent!
Subject: ${inputs.subject}
Sender: ${inputs.email}
Name: ${inputs.name}
Comments: ${inputs.comments}`);
};
const { inputs, handleInputChange, handleSubmit } = useContactForm(message);
export default class ContactForm extends React.Component {
render() {
return (
<div className="contactForm_container">
<div className="contactForm_inner">
<form onSubmit={handleSubmit}>
<div className="input-group">
<label htmlFor="subject">Subject</label>
<input
id="subject"
name="subject"
type="text"
onChange={handleInputChange}
value={inputs.subject}
required
/>
</div>
<div className="input-group">
<label htmlFor="email">Your Email</label>
<input
id="email"
name="email"
type="text"
onChange={handleInputChange}
value={inputs.email}
required
/>
</div>
<div className="input-group">
<label htmlFor="name">Your Name</label>
<input
id="name"
name="name"
type="text"
onChange={handleInputChange}
value={inputs.name}
required
/>
</div>
<div className="input-group">
<label htmlFor="comments">Comments</label>
<textarea
name="comments"
id="comments"
rows={10}
onChange={handleInputChange}
value={inputs.comments}
required
/>
</div>
<div className="controls">
<button type="submit">Send Message</button>
</div>
</form>
</div>
</div>
);
}
}
CustomHook.ts
import React, { useState } from 'react';
/*
This is a Custom React Hook that handles our form submission
*/
const useContactForm = (callback) => {
const [inputs, setInputs] = useState({});
const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
callback();
};
const handleInputChange = (event) => {
event.persist();
setInputs((inputs) => ({
...inputs,
[event.target.name]: event.target.value
}));
};
return {
handleSubmit,
handleInputChange,
inputs
};
};
export default useContactForm;
【问题讨论】:
标签: reactjs typescript react-hooks