将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> $ c中
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>
));