【发布时间】:2018-04-13 10:09:24
【问题描述】:
我将 React 与 TypeScript 一起使用,并且我创建了一个输入组件,它需要大量的道具,其中许多是可选的。到目前为止,我有这个。
interface InputProps {
labelClassName?: string;
labelName?: string;
inputType: string;
inputName?: string;
inputValue: any;
inputOnChange?: (e: any) => void;
readOnly?: boolean;
}
现在,在输入组件中,我想渲染一个带有输入的标签标签。这个输入基本上会继承所有的道具,所以我会有这样的东西。
export class Input extends React.Component<InputProps, {}> {
render() {
console.log(this.props);
return (
<label className={this.props.labelClassName}>
{this.props.labelName}
<input
type={this.props.inputType}
name={this.props.inputName}
value={this.props.inputValue || ""}
readOnly={this.props.readOnly}
onChange={(e) => this.props.inputOnChange(e)} />
</label>)
;
}
}
现在,问题是我不能用 OnChange 写这行,因为 TypeScript 告诉我“对象可能是'未定义'”,这是完全正确的,因为 this.props.inputOnChange 它是一个可选的道具。
所以,我想写的是“如果 this.props.inputOnChange(e) != undefined, 然后在输入中添加 onChange”,但是......我不知道该怎么做。
我试过条件渲染:
{this.props.inputOnChange &&
onChange = {(e) => this.props.inputOnChange(e)} />
但它不起作用
编辑:我发现的一个解决方案是写这样的东西。
let inputOnChange = (this.props.inputOnChange != undefined)
? this.props.inputOnChange
: undefined;
...
<input
...
onChange={inputOnchange} />
但老实说,我不知道是否可以将 undefined 传递给 onChange
【问题讨论】:
-
onChange={ (e) => { if (this.props.inputOnChange) { this.props.inputOnChange(e) } } />
-
完全没问题。
-
我的代码?马丁
标签: javascript reactjs typescript