简体   繁体   中英

Error on passing down function with argument to grandchild in React

I have the following code: My main component is something like this:

class Layout extends React.Component {
  constructor(){
    super()
    this.state={
      searchValue: ''
    }
  }
  getSearchValue(searchValue){
    this.setState({searchValue})
  }
  ...
   return 
     <Filter
       getSearchValue={this.getSearchValue.bind(this)}
     />
  ...
} 

Then I have a child, called Filter:

class Filter extends React.Component {
  ...
  return
     <SearchBar
        getSearchValue={this.props.getSearchValue}
     />
  ...
}

And finally the Search component itself:

class SearchBar extends React.Component {

   handleEvent(e){
     this.props.getSearchValue(e.target.value)
   }
   ...
   return
      <input onChange={this.handleEvent.bind(this)}/>

}

Now, I am pretty sure I had something like this but then I messed it up, and tried to do it back, but now I get an error message:

Uncaught TypeError: this.props.getSearchValue is not a function

Are any of my bindings wrong? I tried several times.

If I put a console.log('Hi') and delete the this.setState() from my getSearchValue in Layout, and I do not pass a variable in SearchBar to this.props.getSearchValue, I get the message to the console. So the function works, but only without arguments. Why?

The coding is correct, except the extra ) in the below statement:

 <Filter
   getSearchValue={this.getSearchValue.bind(this))}
 />

Otherwise, there may be issue in other area of the codes.

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