我需要将 URL 从 class 组件传递到另一个组件

I need to pass a URL from a class component to another

这是我的二维码组件:

import React, { Component } from "react";
class QR extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { catImageUrl } = this.props;
    const qrUrl = `https://qrtag.net/api/qr_12.svg?url=${catImageUrl}`;
    if (!catImageUrl) return <p>Oops, something went wrong!</p>;
    return <img className="QR" src={qrUrl} alt="qrtag" />;
  }
}
export default QR;

我需要将 const qrURL 传递给下一个组件 Form.js 以在 ajax 调用中使用它来获取其数据并将其传递给下一个 api 请求以发送它到电子邮件

class Form extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
    name: '',
    email: '',
    message: '',
  }

  }
  const{qrUrl}=this.props;
  FetchQRURL = () => {
    fetch(`${qrUrl}`)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          message: data,

        });
      })
      .catch((error) => console.log(error));
  };
  handleSubmit(e){
    e.preventDefault();
    axios({
      method: "POST", 
      url:"http://localhost:3002/send", 
      data:  this.state
    }).then((response)=>{
      if (response.data.status === 'success'){
        alert("Message Sent."); 
        this.resetForm()
      }else if(response.data.status === 'fail'){
        alert("Message failed to send.")
      }
    })
  }

  resetForm(){

     this.setState({name: '', email: '', message: ''})
  }

  render() {

    return(
    <div className="App">
    <form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
    <div className="form-group">
        <label htmlFor="name">Name</label>
        <input type="text" className="form-control" id="name" value={this.state.name} onChange={this.onNameChange.bind(this)} />
    </div>
    <div className="form-group">
        <label htmlFor="exampleInputEmail1">Email address</label>
        <input type="email" className="form-control" id="email" aria-describedby="emailHelp" value={this.state.email} onChange={this.onEmailChange.bind(this)} />
    </div>
    <div className="form-group">
        <label htmlFor="message">Message</label>
        <textarea className="form-control" rows="5" id="message" value={this.state.message} onChange={this.onMessageChange.bind(this)} />
    </div>
    <button type="submit" className="btn btn-primary" onClick="">Submit</button>
    </form>
    </div>
    );
  }

  onNameChange(event) {
    this.setState({name: event.target.value})
  }

  onEmailChange(event) {
    this.setState({email: event.target.value})
  }

  onMessageChange(event) {
    this.setState({message: event.target.value})
  }
}

export default Form;

你可以看到我试图将它作为道具传递,但它不起作用

这里我尝试将它作为道具传递(在我的 app.js 中)

import React, { Component } from "react";
import RandomCat from "./RandomCat.js";
import QR from "./QR.js";
import Form from "./form.js";

class BooksApp extends Component {

  state = {
    showCatImage: false,
    showQrCode: false,
    catImageUrl: "",

  };


  handleFetchRandomImage = () => {
    fetch("https://aws.random.cat/meow")
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          catImageUrl: data.file,
          showCatImage: true,
        });
      })
      .catch((error) => console.log(error));
  };


  handleShowQrCode = () => {
    this.setState({ showQrCode: true });
  };



  render() {
    const { showCatImage, showQrCode, catImageUrl,qrUrl } = this.state;

    return (
      <div className="app">
        <div className="first">
          {/* The time below shows cat image if showCatImage === true and returns nothing if false */}
          {showCatImage && <RandomCat catImageUrl={catImageUrl} />}

          <button className="catButton" onClick={this.handleFetchRandomImage}>
            Generate Cat
          </button>
        </div>
        <div className="second">
          {showQrCode && <QR catImageUrl={catImageUrl} qrUrl={qrUrl}/>}

          <button className="QRButton" onClick={this.handleShowQrCode}>
            Geanerate QR
          </button>

        </div>
      <div>
        <Form qrUrl={qrUrl}/>
      </div>
      </div>
    );
  }
}
export default BooksApp;

知道如何将它传递给 Form.js 吗?

您必须将常量 qrUrl 拉到父组件,在您的情况下是 BooksApp

将其设置为状态并将其作为道具传递下去。

state = {
    showCatImage: false,
    showQrCode: false,
    catImageUrl: "",
    qrUrl: ""
};

handleFetchRandomImage = () => {
    fetch("https://aws.random.cat/meow")
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          catImageUrl: data.file,
          showCatImage: true,
          qrUrl: `https://qrtag.net/api/qr_12.svg?url=${data.file}` // Set it here
        });
      })
      .catch((error) => console.log(error));
  };

 handleShowQrCode = () => {
    this.setState({ showQrCode: true });
  };



  render() {
    const { showCatImage, showQrCode, catImageUrl, qrUrl } = this.state;

    return (
      <div className="app">
        <div className="first">
          {/* The time below shows cat image if showCatImage === true and returns nothing if false */}
          {showCatImage && <RandomCat catImageUrl={catImageUrl} />}

          <button className="catButton" onClick={this.handleFetchRandomImage}>
            Generate Cat
          </button>
        </div>
        <div className="second">
          {showQrCode && <QR catImageUrl={catImageUrl} qrUrl={qrUrl}/>}

          <button className="QRButton" onClick={this.handleShowQrCode}>
            Geanerate QR
          </button>

        </div>
      <div>
        <Form qrUrl={qrUrl}/>
      </div>
      </div>
    );
  }
}

export default BooksApp;

只需在您的其他组件中与 this.props.qrUrl 一起使用即可。