将props传递给withRouter()函数中包含的react组件 [英] Passing props to a react component wrapped in withRouter() function

查看:472
本文介绍了将props传递给withRouter()函数中包含的react组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React-Router v4在我的React应用程序中导航。以下是包含在 withRouter()函数中的组件,以便能够在点击时更改路线:

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

如你所见,我传递道具到组件,我需要更改组件的类。这里的问题是在< LogoName> props undefined $ c>组件。当我点击另一个组件时,我需要能够更改此组件的类,如下所示:

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

我有办法传递道具到包含在 withRouter()函数内的组件,或者是否有类似的方法来创建一个能够使用React-导航的组件路由器仍然收到道具?

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?

提前致谢。

推荐答案

问题在于,在解构时,你想要 destructure props 但是你没有将名为 props 的道具传递给 LogoName 组件

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

您可以将参数更改为

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

然而,您仍然可以使用扩展运算符语法建议像@Danny那样构建道具

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

这篇关于将props传递给withRouter()函数中包含的react组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆