简体   繁体   中英

Pass data from input field

I want to take data from an input field and pass it into a to Generate QR code. When I pass the value as a text its work. But can't pass the input value. Does anyone have a simple example of this working?

import React, {Component} from 'react'
import QrCode from 'react.qrcode.generator'

class DemoEdit extends Component {
  constructor() {
    super();  
    this.state = {
      topicIn: "",
      topicOut:""
    };
    this.handleChange=this.handleChange.bind(this);
    this.generate=this.generate.bind(this);
  }

  handleChange ({ target}){
    this.setState({
      [target.name] : target.value
    })
  }

    generate(){
        
       this.setState({
         topicOut:this.state.topicIn
       })
       
     }
     
  render() {
    
    return <div>
    <input 
    type="text" 
    name="topicIn"
    placeholder="Enter Text Here..."
    value={this.state.topicIn}
    onChange={this.handleChange}
    />
<button value="Send" onClick={this.generate}>Generate</button>
      <p>{this.state.topicOut}</p>
      <QrCode value={this.state.topicOut}/>
    </div>
  }
}

export default DemoEdit;

Use a different package. I just tried qrcode.react

import React, { Component } from "react";
import QrCode from "qrcode.react";

class DemoEdit extends Component {
  constructor() {
    super();
    this.state = {
      topicIn: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange({ target }) {
    console.log("value", target.value);

    this.setState({
      topicIn: `${target.value}`
    });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          name="topicIn"
          placeholder="Enter Text Here..."
          value={this.state.topicIn}
          onChange={this.handleChange}
        />
        <QrCode value={this.state.topicIn} />
      </div>
    );
  }
}

export default DemoEdit;

or as a more fancy functional component with hooks, which I totally recommend to use

import React, { useState } from "react";
import QrCode from "qrcode.react";

const DemoEdit = () => {
  const [topicIn, setTopicIn] = useState("");

  const onChange = (event) => setTopicIn(event.target.value);

  return (
    <div>
      <input
        type="text"
        name="topicIn"
        placeholder="Enter Text Here..."
        value={topicIn}
        onChange={onChange}
      />
      <QrCode value={topicIn} />
    </div>
  );
};

export default DemoEdit;

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