gpt4 book ai didi

reactjs - 接受 TextArea 和 Input 的 onChange 的 Typescript 和 React 组件

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:38 28 4
gpt4 key购买 nike

我是 typescript 的新手,我正在尝试创建一个输入组件,如果它接收到 type="text" 它会呈现一个 input 如果它接收到type="textarea" 它呈现出一个 textarea。问题是当我在我的代码中将组件与 onChange 一起使用时, typescript 会提示,它似乎不允许我在同一事件上使用两种类型?

它告诉我:

Type '(e: ChangeEvent<HTMLInputElement>) => void' is not assignable to type '(e?: ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLTextAreaElement> | undefined) => void'.
Types of parameters 'e' and 'e' are incompatible.
Type 'ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLTextAreaElement> | undefined' is not assignable to type 'ChangeEvent<HTMLInputElement>'.
Type 'undefined' is not assignable to type 'ChangeEvent<HTMLInputElement>'.

输入.js

interface InputProps {
className?: string;
type?: string;
placeholder?: string;
onChange?: (e?: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
}

const Input: FunctionComponent<InputProps> = ({ type = 'text', ...props }) => {
if (type === 'textarea') {
return <textarea {...props} />;
}
return <input type={type} {...props} />;
};

用法:

class Usage extends React.Component<State> {
state: State;

onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ input: e.target.value });
};

render() {
return (
<Input placeholder="Write an something..." onChange={this.onInputChange} />
);
}
}

我该如何解决?


更新

目前我解决它的方法是说事件可以是 any 类型,但这是一种 hack

type CommonProps = {
className?: string;
placeholder?: string;
type?: string;
onChange?: (e: any) => void;
};

最佳答案

您可以使用可区分的联合来传递两种类型的参数,一种用于text,另一种用于textarea。这具有确保处理程序和类型同步的额外好处。

type InputProps = { // The common Part
className?: string;
placeholder?: string;
} & ({ // The discriminated union
type?: "text";
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
} | {
type: "textarea";
onChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
})

const Input: FunctionComponent<InputProps> = (props: InputProps) => {
if (props.type === 'textarea') {
return <textarea {...props} />;
}
return <input {...props} />;
};


class Usage extends React.Component<State> {
state: State;

onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ input: e.target.value });
};

render() {
return (
<Input placeholder="Write an something..." onChange={this.onInputChange} />
);
}
}

关于reactjs - 接受 TextArea 和 Input 的 onChange 的 Typescript 和 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943737/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com