简体   繁体   English

如何将价值从一个组件发送到另一个组件

[英]How to send value from one component, to another

I have this prop in one of my components, which I'd like to pass to one other component and use as a variable there:我在我的一个组件中有这个道具,我想将它传递给另一个组件并在那里用作变量:

const VerContinentToolbar = (props) => {


   return (
     <Menu className="nav-icon">
       <CountryList displayFields={["countryName"]} />
     </Menu>
   );
 };

If I console.log(props.props), I get this: https://imgur.com/a/HnRHDcH This is the value that I want to pass to useCountries.如果我 console.log(props.props),我得到这个: https://imgur.com/a/HnRHDcH这是我想传递给 useCountries 的值。 The receiving component looks like this:接收组件如下所示:

const useCountries = (props) => {
    const [countries, setCountries] = useState([])


    useEffect(() => {
        firebase
            .firestore()
            .collection("Africa")
            .onSnapshot((snapshot) => {
                const newCountries = snapshot.docs.map((doc) => ({
                    id: doc.id,
                    ...doc.data()
                }))
                setCountries(newCountries)
            })
    }, [])
    return countries
}



const CountryList = ({ displayFields = [] }) => {
    const countries = useCountries();
    console.log(countries)

    return (
        <div className="countries">
            {countries.map(country => (
                <div key={country.id}>

                    <div className="entry">

                        {displayFields.includes("continent") && (
                            <div>Name of continent: {country.continent}</div>

                        )}
                        {displayFields.includes("revName") && (
                            <div>{country.revName}</div>
                        )}
                        {displayFields.includes("countryName") && (
                            <div><Link to={"./Jumbotron"}>{country.countryName}</Link></div>
                        )}
                        {displayFields.includes("dest1") && (
                            <div>Destination 1: {country.dest1}</div>
                        )}
                        {displayFields.includes("dest2") && (
                            <div>Destination 2: {country.dest2}</div>
                        )}
                        {displayFields.includes("dest3") && (
                            <div>Destination 3: {country.dest3}</div>
                        )}
                        {displayFields.includes("beerPrice") && (
                            <div>Beer price: {country.beerPrice}</div>
                        )}
                        {displayFields.includes("foodPrice") && (
                            <div>Food price: {country.foodPrice}</div>
                        )}
                        {displayFields.includes("hostelPrice") && (
                            <div>Hostel price: {country.hostelPrice}</div>
                        )}
                        {displayFields.includes("review") && <div>Review: {country.review}</div>}
                        {displayFields.includes("imgUrl") && <img src={country.url} alt="no-img" />}
                    </div>
                </div>
            ))}
        </div>
    );
};

I have tried and tried to understand context, but I cannot really wrap my head around it.我已经尝试并尝试理解上下文,但我无法真正理解它。 I'd like to put the value from props into ".collection("Africa")", but I have no clue how to.我想将道具的价值放入“.collection(“Africa”)”,但我不知道如何去做。 I've read the documentation for it, but I'm too thick headed to understand work it out properly.我已经阅读了它的文档,但是我头脑太笨了,无法正确地理解它。

If there's other solutions, I'm all ears.如果还有其他解决方案,我会全力以赴。

What the props that I'd like to pass on is: I've created one component for each continent.我想传递的道具是:我为每个大陆创建了一个组件。 In each component, I call the VerContinentToolbar, passing the prop/name of the continent, like this:在每个组件中,我调用 VerContinentToolbar,传递大陆的属性/名称,如下所示:

const Africa = ({}) => {

  return (
    <div>
      <VerContinentToolbar props={["Africa"]} />
This means, that

 const VerContinentToolbar = (props) => {

   return (
     <Menu className="nav-icon">
       <CountryList displayFields={["countryName"]} />
     </Menu>
   );
 };

Holds the word "Africa".持有“非洲”一词。

I'd like to pass on "Africa", to my component, which fetches the collection of the continent (in this case: Africa).我想将“Africa”传递给我的组件,该组件获取该大陆的集合(在本例中为非洲)。

I want to pass the information that the prop helds to this:我想将道具持有的信息传递给这个:

const useCountries = (props) => {
    const [countries, setCountries] = useState([])


    useEffect(() => {
        firebase
            .firestore()
            .collection("Africa") <---- I WANT PROP FROM VERCONT HERE
            .onSnapshot((snapshot) => {
                const newCountries = snapshot.docs.map((doc) => ({
                    id: doc.id,
                    ...doc.data()
                }))
                setCountries(newCountries)
            })
    }, [])
    return countries
}

To clarify this even more, I've attached two pictures.为了更清楚地说明这一点,我附上了两张图片。 Asia: Here, I want to render the collection "Asia", to display each review that belongs to a country within the continent of Asia.亚洲:在这里,我想渲染集合“亚洲”,以显示属于亚洲大陆内一个国家的每条评论。

https://imgur.com/a/bZhQAwz https://imgur.com/a/bZhQAwz

So far, I've created "Imagination land" and attached it to "Africa" in Firebase.到目前为止,我已经创建了“Imagination Land”并将其附加到 Firebase 中的“Africa”。 I want to show this, only in the Africa component.我只想在非洲部分展示这一点。 And obviously, I want to show all the countries with the Asia tag in the Asia component.显然,我想在亚洲组件中显示所有带有亚洲标签的国家。

Thanks谢谢

EDIT: Problem is solved.编辑:问题解决了。

import React, { Component, useState, useEffect } from 'react'
import { Link } from 'react-router-dom';
import firebase from '../config'
import './Countries.css'
import props from './Navbar/VerContinentToolbar';



const useCountries = continent => {
    const [countries, setCountries] = useState([]);
      console.log('continent', continent) // <--- Get it as your first argument
      console.log(continent.toString())

    useEffect(() => {
        firebase
            .firestore()
            .collection(continent.toString())
            .onSnapshot((snapshot) => {
                const newCountries = snapshot.docs.map((doc) => ({

                    id: doc.id,

                    ...doc.data()

                }))
                setCountries(newCountries)

            })
    }, [])

    return countries
}



const CountryList = ({ continent, displayFields = []  }) => {
    const countries = useCountries(continent); // <--- Pass it in here

    return (
        <div className="countries">
            {countries.map(country => (
                <div key={country.id}>

                    <div className="entry">

                        {displayFields.includes("continent") && (
                            <div>Name of continent: {country.continent}</div>

                        )}
                        {displayFields.includes("revName") && (
                            <div>{country.revName}</div>
                        )}
                        {displayFields.includes("countryName") && (
                            <div><Link to={"./Jumbotron"}>{country.countryName}</Link></div>
                        )}
                        {displayFields.includes("dest1") && (
                            <div>Destination 1: {country.dest1}</div>
                        )}
                        {displayFields.includes("dest2") && (
                            <div>Destination 2: {country.dest2}</div>
                        )}
                        {displayFields.includes("dest3") && (
                            <div>Destination 3: {country.dest3}</div>
                        )}
                        {displayFields.includes("beerPrice") && (
                            <div>Beer price: {country.beerPrice}</div>
                        )}
                        {displayFields.includes("foodPrice") && (
                            <div>Food price: {country.foodPrice}</div>
                        )}
                        {displayFields.includes("hostelPrice") && (
                            <div>Hostel price: {country.hostelPrice}</div>
                        )}
                        {displayFields.includes("review") && <div>Review: {country.review}</div>}
                        {displayFields.includes("imgUrl") && <img src={country.url} alt="no-img" />}



}
                    </div>
                </div>

            ))}
        </div>
    );
};


export default CountryList
const VerContinentToolbar = (props) => {

  return (
    <Menu className="nav-icon">
      <CountryList
        continent={props.continent}
        displayFields={["countryName"]}
      />
    </Menu>
  );
};

Thanks for all your help.感谢你的帮助。

  1. Pass it as a prop (continent) from your continent component将它作为来自您的大陆组件的道具(大陆)传递

    const Africa = () => { return ( <div> <VerContinentToolbar continent="Africa" /> </div> ); };
  2. In <VerContinentToolbar /> , get the prop and pass it down to <CountryList /> .<VerContinentToolbar />中,获取道具并将其传递给<CountryList /> Rather than passing props down to grandchildren components you can use the context API for that or Redux for that.您可以使用上下文 API或 Redux ,而不是将道具传递给孙子组件。

     const VerContinentToolbar = props => { console.log('continent prop is now here', props.continent) return ( <Menu className="nav-icon"> <CountryList continent={props.continent} displayFields={["countryName"]} /> </Menu> ); };
  3. In <CountryList /> , get the prop ( continent ) and pass it into your useCountries hook.<CountryList />中,获取道具( continent )并将其传递到您的useCountries挂钩中。

     const CountryList = props => { const countries = useCountries(props.continent); // <--- Pass it in here console.log(countries) return ( <div className="countries"> {countries.map(country => ( {/*...code */} ))} </div> ); };
  4. And finally in your hook get it as the first argument最后在你的钩子里把它作为第一个参数

    const useCountries = continent => { const [countries, setCountries] = useState([]); console.log('continent', continent) // <--- Get it as your first argument //...code return countries }

As I understand your question to be, you want to within CountryList , call the useCountries hook to specify the collection you want.据我了解您的问题是,您想在CountryList中调用useCountries挂钩来指定您想要的集合。

const useCountries = (collection) => {
  const [countries, setCountries] = useState([])

  useEffect(() => {
    firebase
      .firestore()
      .collection(collection) // <-- pass collection argument here
      .onSnapshot((snapshot) => {
        const newCountries = snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data()
        }))
        setCountries(newCountries)
      })
  }, [])
  return countries
}

In CountryList pass the value you want to useCountriesCountryList中传递您要使用的值useCountries

const countries = useCountries('Africa');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在React JS中将一个组件的值发送给另一个组件? - how to send value one component to another component in react js? 如何将数据从一个反应组件发送到另一个反应组件? - How to send data from one react component to another react component? 有没有办法将 Bootstrap Datepicker 值从一个组件发送到另一个组件? - Is there a way to send a Bootstrap Datepicker value from one component to another? 如何从一个组件到另一个组件获取价值? - How to get value from one component to another? 如何将变量的值从一个组件发送到另一个组件? (反应) - How can I send the value of a variable from one component to another? (React) 如何通过上下文将数据从一个组件发送到另一个组件? - how to send data From one component to another components with context in react? 如何在vue中将数组从一个组件发送到另一个组件 - How to send array from one component to another in vue 灰烬:将动作从一个组件发送到另一组件 - Ember: send action from one component to another 在反应中将变量从一个组件发送到另一个组件 - Send variable from one component to another in react 如何在react js中将值从一个组件传递到另一个组件 - how to pass value from one component to another in react js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM