gpt4 book ai didi

reactjs - 类型 'null' 不可分配给类型 'HTMLInputElement' ReactJs

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:33 24 4
gpt4 key购买 nike

我正在尝试将数据与 typescript 一起引用到 reactJS 中。这样做时我遇到了以下错误

Type 'null' is not assignable to type 'HTMLInputElement'

请让我知道这里到底哪里不对,我使用了 React 的 documentaiton https://reactjs.org/docs/refs-and-the-dom.html但我认为我在这里做错了什么。以下是范围片段

  class Results extends React.Component<{}, any> {
private textInput: HTMLInputElement;
.......
constructor(props: any) {
super(props);

this.state = { topics: [], isLoading: false };

this.handleLogin = this.handleLogin.bind(this);
}

componentDidMount() {.....}

handleLogin() {
this.textInput.focus();
var encodedValue = encodeURIComponent(this.textInput.value);
.......
}

render() {
const {topics, isLoading} = this.state;

if (isLoading) {
return <p>Loading...</p>;
}

return (
<div>
<input ref={(thisInput) => {this.textInput = thisInput}} type="text" className="form-control" placeholder="Search"/>
<div className="input-group-btn">
<button className="btn btn-primary" type="button" onClick={this.handleLogin}>

...............

知道我在这里可能遗漏了什么吗?

最佳答案

错误是因为类型定义说输入可以是 nullHTMLInputElement

您可以在 tsconfig.json 中设置 "strict": false

或者你可以强制输入为HTMLInputElement类型

<input ref={thisInput => (this.textInput = thisInput as HTMLInputElement)} type="text" className="form-control" placeholder="Search" />

这种方式也是有效的(using definite assignment assertions (typescript >= 2.7))

<input ref={thisInput => (this.textInput = thisInput!)} type="text" className="form-control" placeholder="Search" />

关于reactjs - 类型 'null' 不可分配给类型 'HTMLInputElement' ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48488701/

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