【问题标题】:Pass values from one component to another将值从一个组件传递到另一个组件
【发布时间】:2021-10-31 15:49:46
【问题描述】:

我有以下 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

【问题讨论】:

    标签: reactjs class react-hooks components


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      为了让您将数据作为 props 传递给另一个组件,相关组件必须是接收数据的组件(子组件)的父组件。这种数据传输通常被称为“通过道具”。为了让您通过道具将数据从一个组件传递到另一个组件,您的父组件必须返回您的子组件:

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

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

      【讨论】:

        【解决方案3】:

        在你的 FriendsList 组件中添加这一行:

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

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

        【讨论】:

        • 我通过将 FriendTagged 添加到 FriendsList 组件中进行了尝试,并且如控制台日志中所见,这些值正在被结转。我编写了这样的代码,以便在单击按钮时进行导航。所以现在所有的值都被传递给 FriendTagged 组件,但在按钮单击时,它会被空道具替换。我希望我清楚这个问题
        • 我编辑了我的帖子,我想你正确地将选中的人添加到this.state.checkedPpl
        • 然后在您的 btn 中,只需将您的应用重定向到呈现 FriendTagged 组件
        猜你喜欢
        • 1970-01-01
        • 2020-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 2021-01-11
        • 2018-03-07
        相关资源
        最近更新 更多