将值从一个组件传递到另一个组件

Pass values from one component to another

我有以下 2 个文件,我需要将状态变量 checkedPpl 的值从一个组件传递到另一个组件。我正在学习 React,任何指点都会有很大帮助。

在这个特定项目中,我通过 FriendsList 中的复选框选择了一些人名,并希望将这些值传递给 FriendTagged 组件。我知道我需要将这些值作为状态变量存储在 FriendsList 中,并将它们作为道具传递给 FriendTagged。请建议如何实现这一目标。

FriendsList.jsx

import React, { Component, useState } from 'react';
import SampleImg from '../assets/SampleImg.jpg';
import styled from 'styled-components';
import {Link} from 'react-router-dom';
//import { BrowserRouter as Router, Route, Switch,withRouter,useHistory } from 'react-router-dom'
import PeopleDataService from '../service/PeopleDataService';
import Checkbox from './Checkbox';
import FriendTagged from './FriendTagged';
import PassValues from '../PassValues';
//import Navbar from './Navbar';





const Button=styled.button`

background-color:#3949ab;
color:white;
padding:5px 15px;
border-radius:5 px;
outline:0;
text-transform:uppercase;
cursor:pointer;
box-shadow:0px 2px 2px lightgray;
`
const ListComp = {
    width: "300px",
    margin: "30px auto",
    backgroundColor: "#44014C",
    minHeight: "200px",
    boxSizing: "border-box"
   }

   const linkStyle = {
    margin: "1rem",
    textDecoration: "none",
    color: '#800020',
    backgroundColor: "#CFB997"
  };

   
   


class FriendsList extends Component {

    constructor(props) {
        super(props)        
        this.state = {
            isLoading:false,
            people: [],
            redirect:false,
            checkedPpl: []
            
        }
        
       console.log("inside constructor "+this.props)
        this.addFriendClicked = this.addFriendClicked.bind(this)
        this.refreshPeople = this.refreshPeople.bind(this)
        this.deleteFriendClicked=this.deleteFriendClicked.bind(this)
        //this.clickMe=this.clickMe.bind(this); 
        
    }
    addFriendClicked() {
        PeopleDataService.addFriendClicked()
       // this.props.history.push(`/save`)
    }
    componentDidMount() {
        this.refreshPeople();
        this.selectedCheckboxes = new Set();
        
        //this.setState({ people: body, isLoading: true });
        
    }
    deleteFriendClicked(){
        PeopleDataService.deleteFriendClicked()
    }
    refreshPeople() {
        
        this.setState({people: ["Jack","Jill","Louis","Emily","Donald","Holly"] })
           // alert(response.data);
    }
    

   /* refreshPeople() {
        PeopleDataService.retrieveAllFriends()//HARDCODED
            .then(
                response => {
                    console.log(response.headers);
                    this.setState({ people: response.data })//["Subin","Fiona","Evana"]
                    //alert(response.data);
                }
            )
           // alert(response.data);
    }*/
    toggleCheckbox = label => {
        console.log("Inside toggle checkbox "+label+this.selectedCheckboxes)
        if (this.selectedCheckboxes.has(label)) {
          this.selectedCheckboxes.delete(label);
        } else {
          this.selectedCheckboxes.add(label);
        }
        this.setState({checkedPpl:[label]})
        //console.log('checkedPpl '+ "***" +label+"(((("+this.checkedPpl)
        console.log(this.state);
      }
    
      handleFormSubmit = formSubmitEvent => {
        formSubmitEvent.preventDefault();
        
    
        for (const checkbox of this.selectedCheckboxes) {
          console.log(checkbox, 'is selected.');
        }
      
      
        //this.setState({ redirect: true })
      }
    
     /*onSubmit = () => {
        {this.handleFormSubmit()};
        console.log("Inside onSubmit")
            this.props.history.push('/FriendTagged');
        
     }*/

      
      createCheckbox = label => (
        <Checkbox
          label={label}
          handleCheckboxChange={this.toggleCheckbox}
          key={label}
        />
      )
    
      createCheckboxes = () => (
        this.state.people.map(this.createCheckbox)
      )
   
    

    render() {
      const {checkedPpl} = this.state;
      console.log("Parent value "+checkedPpl);
        return (       
            
           
                                  
                    <div className="container">
                        
        <h3 style={{ padding: "10px 20px", textAlign: "center", color: "#44014C"}}>Amigos  </h3>
        <div className="imgContainer">
        <h6 style={{ padding: "10px 20px", textAlign: "center", color: "#FF00FF"}}>Choose friends to tag on the photo</h6>
        
        
       <p></p>


        
        </div>

        <div className="tableContainer">
        <img src={SampleImg} width="250" height="200"/>
         <form onSubmit={this.handleFormSubmit} onChange={(e) => { this.setState({ checkedPpl:this.state }) }}> 
        <table className="table">
            
                        <thead>
                            <tr>
                                
                                <th>Name</th>
                                
                                
                            </tr>
                            
                        </thead>
                        <tbody >
                        {
                            
                                
                                          
                                             <tr>                                     
                                            {
                                            this.createCheckboxes()
                                            
                                            }
                                            <Link to="/component/FriendTagged" className="btn btn-default" style={linkStyle} type="submit">Tag</Link>
                                            
                                            
                                           
                                            </tr> 
                                        
                                       /* <tr > This displayed Tag and Remove buttons w/o names of people                                          
                                        <td>{person.name}</td>
                                        <td><button className="button btn-success" onClick={() => this.addFriendClicked(person.id)}>Tag</button></td>
                                        <td><button className="btn btn-warning" onClick={() => this.deleteFriendClicked(person.id)}>Remove</button></td>
                                    </tr>*/
                                        /*<tr key={person.id}>                                            
                                        <td>{person.name}</td>
                                        <td><button className="button btn-success" onClick={() => this.addFriendClicked(person.id)}>Tag</button></td>
                                        <td><button className="btn btn-warning" onClick={() => this.deleteFriendClicked(person.id)}>Remove</button></td>
                                    </tr>*/
                                
                            }
                          
                        </tbody>
                        
                    </table>
                    </form>   
                    </div>
        
                
                    
                </div>
                    
            
        )
    }

    
}

export default FriendsList

FriendTagged.jsx

import React, { Component } from 'react';
import FriendsList from './FriendsList';
import sampleImg from '../assets/SampleImg.jpg';

class FriendTagged extends Component {
    
   

    render() {
        
        return (
            <div className="container">
    <h3 style={{ padding: "10px 20px", textAlign: "center", color: "#44014C"}}>Tagged Together</h3>
        <img src={sampleImg} width="250" height="200"/>
        
        <h6 style={{ padding: "10px 20px", textAlign: "center", color: "#FF00FF"}}>Friends tagged on this photo are:</h6>
        {this.props.data}
        
        
        </div>
        
        )
    }
}

export default FriendTagged

为了将数据作为 props 传递给另一个组件,相关组件必须是接收数据的组件的父组件 - 子组件。这种数据传输通常被称为'passing through props'。为了让您通过道具将数据从一个组件传递到另一个组件,您的父组件必须 return 您的子组件:

const App=()=>{
 const handleSomething=()=>{}
 const handleClick=()=>{}
 const doSomething=()=>{}

 return(
<div>
  <ChildComponent hadleSomething={handleSomething} handleClick={handleClick} doSomething={doSomething}/>
</div>
)

您传递给 ChildComponent 组件的 props 是您从父组件传递给子组件的数据。

在您的 FriendsList 组件中添加此行:

    render() { 
      return (
         ....
        <div>
          <FriendTagged data={this.state.checkedPpl} />
        </div>
        ....
        )
    }

然后在您的 FriendTagged 组件中使用 {this.props.data} 来恢复您的数据。

您可以使用路由状态通过路由转换发送值。

Link to: object

<Link
  to={{
    pathname: "/component/FriendTagged",
    state: {
      friends: this.state.checkedPpl, // <-- pass the state here
    }
  }}
  className="btn btn-default"
  style={linkStyle}
  type="submit"
>
  Tag
</Link>

在接收组件中,FriendTagged,通过 location 属性访问路由状态。

Route props

const { state } = this.props.location;
const { friends } = state;

旁注

您似乎在 toggleCheckbox 中有一个错误,您没有在 this.state.checkedPpl 状态数组中添加或删除选中的人,而是始终将其设置为仅包含最后切换的值,无论检查状态如何。你也想解决这个问题。

this.setState({ checkedPpl: [label] })