简体   繁体   中英

How to get value from element in react js?

This is my very first app in React. I have created the component and when a user adds text to textArea and clicks on the button, "Download Pdf", I want to pass defaultValue to convertToPdf function.

How do i do that? Basically, I am trying to create a PDF downloader. Any help will be appreciated.

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>
    );
  }
}

Bulletpoints:

  1. Actually create a ref for your textarea (in constructor)
constructor(props) {
    super(props);

    this.textareaRef = React.createRef();
}

then pass it to your textarea element like this

ref={this.textareaRef}
  1. In your convertToPdf() use it like so
this.setState({value: this.textareaRef.current.value})
  1. React state consists of key-value pairs, so you should initialize it in constructor like so
this.state = {
    value: null;
}

and then whenever you want to change it (only from within this component), you call setState(), like I did in p. 2

  1. You are mixing html elements with JS variables: you can't call this.textarea, because it's not a variable (nor constant), so remove all such references to it. In React the only way to access DOM elements is by refs (which you already kind of tried, I corrected you in p. 1).

Enjoy React, it's great:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM