如何在React中将函数传递给另一个组件

时间:2019-01-23 01:48:17

标签: javascript reactjs

我是新来的反应者,所以我有以下内容:

应用程序组件,该组件具有一个称为performSearch的功能,它还呈现了Header组件

//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

这是Header组件,我想做的就是给Header中的Nav组件提供来自App组件的performSearch函数,例如<Nav onSearch={this.performSearch }/> {/*Render Nav menu and pass performSearch function */}我试图将该函数传递给Header中的Nav,但是没有工作,有人可以帮忙吗?

/* 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;

2 个答案:

答案 0 :(得分:2)

问题是您正在使用this.performSearch,就像在Nav组件中定义了该函数一样,事实并非如此。您需要将performSearch函数从App传递到Nav

应用程序组件

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

标题组件

// 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>
    );
};

请注意,您需要将props定义为功能Header组件的参数才能访问performSearch

您还可以使用对象解构语法直接访问函数:

标题组件(使用对象分解)

// 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>
    );
};

答案 1 :(得分:1)

您需要将执行搜索传递到标头组件,然后传递给导航组件。否则,您的导航组件将无法访问performSeach。此外,在传递performSearch时使用bind或箭头功能,否则perFormSearch不会在您的应用程序组件上下文中执行。

//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;