简体   繁体   中英

How to pass a function into another component in react

I am new to react, so I have the following component:

App component this component has a function called performSearch, it also renders a Header component

//this function will create the search feature
  performSearch = (text = 'dogs') => { //include text parameter from flickr api on url, and provide a default value for text parameter to display dog pics when the page first loads
     //fetch data from flickr
     axios
     .get(
       `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&text=${text}&per_page=24&format=json&nojsoncallback=1`
     )
     .then(response => {
       this.setState({
         pics: response.data.photos.photo
       });
     })
     .catch(error => {
       console.log("Something went wrong, could not access data", error);
     });
  };


  render() {
    //console.log(this.state.pics);
    return (
      //JSX inside ()
      <BrowserRouter>
        <div>
          <Header  //Render Header Component
          />

          <GalleryItem data={this.state.pics} />
          {/*pass data array to GalleryItem component */}
        </div>
      </BrowserRouter>
    );
  }
} //closes App

this is the Header component, what I would like to do is give the Nav component inside Header the performSearch function from App component like this <Nav onSearch={this.performSearch }/> {/*Render Nav menu and pass performSearch function */} I tried to pass that function to Nav located in Header, but it wasn't working, could someone help?

/* import react*/
import React from "react";

//import modules
import Form from "./Form";
import Nav from "./Nav";
import Gallery from "./Gallery";
// import Galleryitem from './Galleryitem'

/*Create a Header component that could store things 
like an app title, logo, nav and search bar.
 */
const Header = () => {
  return (
    //JSX inside ()
    <header>
      <Form /> {/*render the search bar*/}
       <Nav /> {/*Render Nav menu */}
      <Gallery /> {/*Render Gallery component  */}
    </header>
  );
};

/*Now export Header component so that we are able to import it 
  and use it within other components or modules of our app*/
export default Header;

The problem is you are using this.performSearch as if such function were defined inside the Nav component and thats not the case. You to have pass down the performSearch function from the App to the Nav :

App component

render() {
    //console.log(this.state.pics);
    return (
        //JSX inside ()
        <BrowserRouter>
            <div>
                {/* Pass the function as a prop down to Header */}
                <Header onSearch={this.performSearch}/>

                <GalleryItem data={this.state.pics} />
                {/*pass data array to GalleryItem component */}
            </div>
        </BrowserRouter>
    );
}

Header component

// Accept component properties as first parameter
const Header = (props) => {
    return (
        //JSX inside ()
        <header>
            <Form /> {/*render the search bar*/}
                <Nav onSearch={props.onSearch}/> {/*Render Nav menu */}
            <Gallery /> {/*Render Gallery component  */}
        </header>
    );
};

Note that you need to define props as a parameter of the functional Header component in order to access performSearch .

You could also use object destructuring syntax for accesing the function directly:

Header component (using object destructuring)

// Accept component properties as first parameter
const Header = ({ onSearch }) => {
    return (
        //JSX inside ()
        <header>
            <Form /> {/*render the search bar*/}
                <Nav onSearch={onSearch}/> {/*Render Nav menu */}
            <Gallery /> {/*Render Gallery component  */}
        </header>
    );
};

You need to pass perform search to your header component, and then to your nav component. Otherwise your nav component has no way of accessing performSeach. In addition, either use bind, or an arrow function when passing performSearch, or perFormSearch will not execute in your app components context.

//this function will create the search feature
  performSearch = (text = 'dogs') => { //include text parameter from flickr api on url, and provide a default value for text parameter to display dog pics when the page first loads
     //fetch data from flickr
     axios
     .get(
       `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&text=${text}&per_page=24&format=json&nojsoncallback=1`
     )
     .then(response => {
       this.setState({
         pics: response.data.photos.photo
       });
     })
     .catch(error => {
       console.log("Something went wrong, could not access data", error);
     });
  };


  render() {
    //console.log(this.state.pics);
    return (
      //JSX inside ()
      <BrowserRouter>
        <div>
          <Header performSearch={this.performSearch.bind(this)}  //Render Header Component
          />

          <GalleryItem data={this.state.pics} />
          {/*pass data array to GalleryItem component */}
        </div>
      </BrowserRouter>
    );
  }
} //closes
import React from "react";

//import modules
import Form from "./Form";
import Nav from "./Nav";
import Gallery from "./Gallery";
// import Galleryitem from './Galleryitem'

/*Create a Header component that could store things 
like an app title, logo, nav and search bar.
 */
const Header = ({ performSearch, }) => {
  return (
    //JSX inside ()
    <header>
      <Form /> {/*render the search bar*/}
       <Nav onSearch={performSearch}/> {/*Render Nav menu */}
      <Gallery /> {/*Render Gallery component  */}
    </header>
  );
};

/*Now export Header component so that we are able to import it 
  and use it within other components or modules of our app*/
export default Header;


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM