簡體   English   中英

如何將數據從一個頁面傳遞到另一個 React JS

[英]How can I pass data from one page to another React JS

我是 React 新手,我正在做一個項目。 我有兩個頁面/組件。 我在頁面上獲取用戶的詳細信息,並希望在另一個頁面上顯示數據。 但我做不到。 有人可以幫忙嗎。

這是我的第一頁Personal.js


import React from "react";
import { Form, Row, Col, Button } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
// import bootstrap from "bootstrap";
import { Link } from "react-router-dom";


class Personal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    };
  }

  render() {
    return (
      <>
        <h2 className="text-center my-4">Personal Information</h2>

        <div expand="md" className="container my-4 ">
          <Form >
            <Row className="my-4">
              <Col>
                <Form.Label>First Name</Form.Label>
                <Form.Control id="first_name" placeholder="First name" />
              </Col>
              
            </Row>

           
            <Link to="/Final">
              <Button
                onClick={() =>
                  this.setState({
                    name: document.getElementById("first_name").value,})}
                variant="outline-primary">{" "}Next</Button>{" "}
            </Link>
          </div>
        </div>
      </>
    );
  }
}

export default Personal;

這是我的第二頁Final.js

import React from "react";
import { Link } from "react-router-dom";

const Final = (props) => {
  return (
    <>
      <h2>Your Name{this.props.name}</h2>   
     
    </>
  );
};

export default Final;

這可能不是解決問題,而是你的Final部件是一個功能組件,它接受props作為參數,所以不是this.props.name你只需訪問props.name 我也無法弄清楚您在呈現 Button 組件的地方使用{" "}引號是怎么回事?

Personal您要在該組件的狀態上設置 name 值,因此您需要在Personal呈現Final以便向下傳遞該值,或者為它們提供一個公共來源以從中讀取該數據,例如Context或 common父級(如<App>組件)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM