简体   繁体   中英

Passing props to a react component wrapped in withRouter() function

I am using React-Router v4 to navigate in my React app. The following is a component wrapped in the withRouter() function to make it able to change route on click:

const LogoName = withRouter(({history, props}) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

As you can see I pass the props to the component, which I need in order to change the class of the component. The problem here is that props is undefined in the <LogoName> component. I need to be able to change the class of this component when I click on another component, like this:

<LogoName className={this.state.searchOpen ? "hidden" : ""} />
<div id="search-container">
  <SearchIcon
    onClick={this.handleClick}
    className={this.state.searchOpen ? "active" : ""} />
  <SearchBar className={this.state.searchOpen ? "active" : ""}/>
</div>

Here is how I handle the click. Basically just setting the state.

constructor(){
  super();
  this.state = {
    searchOpen: false
  }
}

handleClick = () => {
  this.setState( {searchOpen: !this.state.searchOpen} );
}

Is there a way for me to pass props to a component that is wrapped inside the withRouter() function or is there a similar way to create a component which has the ability to navigate with React-Router and still receive props?

Thanks in advance.

The problem is that while destructuring, you want to destructure props but you are not passing any prop named props to LogoName component

You can change your argument to

const LogoName = withRouter((props) => (
  <h1
    {...props}
    onClick={() => {props.history.push('/')}}>
    BandMate
  </h1>
));

However you can still destructure the props like @Danny also suggested by using the spread operator syntax like

const LogoName = withRouter(({history, ...props}) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

You're close, just spread the props in your function signature as well:

const LogoName = withRouter(({ history, ...props }) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

This worked for me:

import  {withRouter} from 'react-router-dom';
class Login extends React.Component
{
   handleClick=()=>{
      this.props.history.push('/page');
   }
   render()
  {
     return(
          <div>
          .......
            <button onClick={this.handleClick()}>Redirect</button>
          </div>);
  }
}

export default withRouter(({history})=>{
  const classes = useStyles();
    return (
        <Login  history={history} classes={classes} />
    )
});

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