javascript - 在 TypeScript 中使用 React.findDOMNode

标签 javascript typescript reactjs

我正在关注 React Tutorial并卡在如何使用 React.findDOMNode 上.

这是我的代码:

export class CommentForm extends React.Component<{}, {}> {
    handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        console.log(React.findDOMNode(this.refs['author']));
    }

    render() {
        return <form className="commentForm" onSubmit={ e => this.handleSubmit(e) }>
                 <input type="text" placeholder="Your name" ref="author" />
                 <input type="text" placeholder="Say something..." ref="text" />
                 <input type="submit" value="Post" />
               </form>;
    }
}

调用 console.log(React.findDOMNode(this.refs['author']));还我<input type="text" data-reactid=".0.2.0" placeholder="Your name"> 在控制台中。 但是,我不知道如何检索输入元素的值(我在输入框中键入的内容)。

到目前为止,我已经与其他一些人一起尝试了以下方法:

React.findDOMNode(this.refs['author']).value; // "value" does not exist on type "Element"
React.findDOMNode(this.refs['author']).getAttribute('value'); // null
React.findDOMNode(this.refs['author']).textContent; // null

在 intellisense 中我可以看到以下内容,但我仍然不知道在这里调用什么。 enter image description here

我正在使用 DefinitedlyTyped 中的类型定义. 另外,我是前端开发的新手,所以我的方法可能是错误的。

最佳答案

请注意,本教程是用 JavaScript 而不是 TypeScript 编写的。

但是,我找到了正确执行此操作的解决方案(OP 的回答非常麻烦)。基本上,您必须对教程代码进行两处更改。作为引用,这是我编写本文时教程中的代码:

var author = React.findDOMNode(this.refs.author).value.trim();

第一个变化是:

this.refs.author

成为

this.refs["author"]

我是 TypeScript 的新手,但我认为它更喜欢您使用索引器语法而不是属性语法来处理那些意味着没有前向声明其真实属性的对象。

其次,也是最重要的,

React.findDOMNode

成为

React.findDOMNode<HTMLInputElement>

基本上,在这里我们必须明确告诉 TypeScript 我们请求的是什么类型的元素。使用您的代码完成查找可用元素的完整列表。我假设它涵盖了所有内部组件。

这是最后的工作代码行:

var author = React.findDOMNode<HTMLInputElement>(this.refs["author"]).value.trim();

为方便起见,这里是该方法在本教程中首次出现之前的完整方法(略微重构以避免调用 findDOMNode 两次):

handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    var authorInput = React.findDOMNode<HTMLInputElement>(this.refs["author"]);
    var textInput = React.findDOMNode<HTMLInputElement>(this.refs["text"]);

    var author = authorInput.value.trim();
    var text = textInput.value.trim();

    if (!text || !author)
        return;

    authorInput.value = textInput.value = "";
}

关于javascript - 在 TypeScript 中使用 React.findDOMNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480321/

相关文章:

javascript - 如何更改选择行时的行颜色?

typescript - 类属性 - 点或等号

javascript - 将 nuxt 3 从 TypeScript 迁移到 JavaScript

reactjs - Jest - 如何测试 react 方法的输出是否正确?

javascript - 比较时选择唯一的数组值

javascript - Function.prototype.call.call 的简写?

javascript - Bootstrap tooltip 和 popover 在同一个元素上

typescript - 为什么 any 会在没有强制转换的情况下转换为更具体的类型

reactjs - 如何更改 React map 中的渲染顺序

javascript - 提供的目标来源与收件人窗口的来源不匹配(Rocket 聊天)