React.js 的状态和事件有哪些类型?
在我下面的代码中,我只能通过使用来使其工作,type: any但这只是一个 hack。我怎样才能为他们使用正确的类型?
在我的自定义钩子中:
如果我使用function useFormFields(initialState: object),我会得到:
// value={inputs.item} error:
Property 'item' does not exist on type 'object'.ts(2339)
// onChange function error:
(JSX attribute) onChange: object
No overload matches this call.
如果我使用function(event: React.FormEvent)(这是真的),我有这个错误:
Property 'id' does not exist on type 'EventTarget'.ts(2339)
如果我使用function(event: object),我有这个错误:
Property 'target' does not exist on type 'object'.ts(2339)
这很奇怪,因为我在下面使用const handleSubmitItem = (event: React.FormEvent)它并且它有效。
我找到的答案(比如这个)对我不起作用,因为Property 'id' does not exist on type 'EventTarget'
import React, {useState} from 'react';
import TextField from '@material-ui/core/TextField';
import IconButton from '@material-ui/core/IconButton';
import AddShoppingCartIcon from '@material-ui/icons/AddShoppingCart';
/**
 * Custom hooks for input fields.
 * @param initialState initialState for Input Fields
 */
function useFormFields(initialState: any) {
    const [inputs, setValues] = useState(initialState);
    return [
        inputs,
        function(event: any) {
            setValues({
                ...inputs,
                [event.target.id]: event.target.value
            });
        }
    ];
}
export default function FormPropsTextFields() {
    const [inputs, handleInputChange] = useFormFields({
        item: '',
        quantity: '',
        store: ''
    });
    const handleSubmitItem = (event: React.FormEvent) => {
        event.preventDefault();
        console.log(inputs);
    };
    return (
        <form 
            className={classes.root} 
            noValidate autoComplete="off"
            onSubmit={handleSubmitItem}
        >
            <div>
                <TextField 
                    required id="item" 
                    label="Item" 
                    value={inputs.item}
                    onChange={handleInputChange}
                />
                <TextField
                    id="quantity"
                    label="Quantity"
                    type="number"
                    value={inputs.quantity}
                    onChange={handleInputChange}
                    InputLabelProps={{
                        shrink: true,
                    }}
                />
                <TextField 
                    id="store" 
                    label="Store" 
                    type="search"
                    value={inputs.store}
                    onChange={handleInputChange}
                />
                <IconButton 
                    type="submit"
                    color="primary" 
                    aria-label="add to shopping cart"
                >
                    <AddShoppingCartIcon />
                </IconButton>
            </div>
        </form>
    );
}