首页 > 解决方案 > 如何从 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>
    );
  }
}

标签: javascriptreactjs

解决方案


要点:

  1. 实际上为您的 textarea 创建一个 ref(在构造函数中)
constructor(props) {
    super(props);

    this.textareaRef = React.createRef();
}

然后像这样将它传递给你的 textarea 元素

ref={this.textareaRef}
  1. 在你的 convertToPdf() 中像这样使用它
this.setState({value: this.textareaRef.current.value})
  1. React 状态由键值对组成,因此您应该像这样在构造函数中对其进行初始化
this.state = {
    value: null;
}

然后每当你想改变它时(只在这个组件中),你调用 setState(),就像我在 p 中所做的那样。2

  1. 您将 html 元素与 JS 变量混合在一起:您不能调用 this.textarea,因为它不是变量(也不是常量),因此请删除对它的所有此类引用。在 React 中,访问 DOM 元素的唯一方法是通过 refs(您已经尝试过,我在第 1 页更正了您)。

享受 React,它很棒 :)


推荐阅读