javascript - 如何从 React js 中的元素获取价值?
问题描述
这是我在 React 中的第一个应用程序。我已经创建了组件,当用户将文本添加到 textArea 并单击“下载 Pdf”按钮时,我想将 defaultValue 传递给convertToPdf
函数。
我怎么做?基本上,我正在尝试创建一个 PDF 下载器。任何帮助将不胜感激。
pdfComponent.js
import React, { Component } from "react";
import autosize from "autosize";
import Button from '@material-ui/core/Button';
export class PDFEditorComponent extends Component {
componentDidMount() {
this.textarea.focus();
autosize(this.textarea);
}
convertToPdf() {
this.setState(this.textarea);
console.log("TEXT", this.textarea);
}
render() {
const style = {
maxHeight: "175px",
minHeight: "450px",
minWidth: "800px",
resize: "none",
padding: "9px",
boxSizing: "border-box",
fontSize: "15px"
};
return (
<div>
PDF Downloader
<br />
<br />
<textarea
style={style}
ref={c => (this.textarea = c)}
placeholder="Paste pdf data"
rows={1}
defaultValue=""
/>
<br />
<Button
variant="contained"
color="primary"
onClick={() => this.convertToPdf(this.textarea)}
>
Download Pdf
</Button>
</div>
);
}
}
解决方案
要点:
- 实际上为您的 textarea 创建一个 ref(在构造函数中)
constructor(props) {
super(props);
this.textareaRef = React.createRef();
}
然后像这样将它传递给你的 textarea 元素
ref={this.textareaRef}
- 在你的 convertToPdf() 中像这样使用它
this.setState({value: this.textareaRef.current.value})
- React 状态由键值对组成,因此您应该像这样在构造函数中对其进行初始化
this.state = {
value: null;
}
然后每当你想改变它时(只在这个组件中),你调用 setState(),就像我在 p 中所做的那样。2
- 您将 html 元素与 JS 变量混合在一起:您不能调用 this.textarea,因为它不是变量(也不是常量),因此请删除对它的所有此类引用。在 React 中,访问 DOM 元素的唯一方法是通过 refs(您已经尝试过,我在第 1 页更正了您)。
享受 React,它很棒 :)
推荐阅读
- html - HTML 电子邮件的 VS Code 美化器
- java - 当测试被忽略时失败
- mysql - Mysql:将选定的列复制到另一个表
- python - 有没有办法使用网站自己的下拉菜单来抓取更多结果?
- javascript - Chartjs 图表仅在单击按钮两次后才调整大小
- firebase - 如何在 Flutter Modular 中设置 RouteGuard 以进行 Firebase 身份验证
- sql - 从 SQL Server 向 HTML 字符串添加类和 onclick 函数
- java - 部署到 Heroku 的 Spring App 中的日期加载问题
- java - SpringData JPA“AND”和“OR”查询未按预期工作
- loops - VBA - 两个日期之间的场景分析 - 如何添加观察窗口不重叠的条件