【发布时间】:2018-02-20 13:03:34
【问题描述】:
我有一个可以在项目的所有页面上查看的搜索栏组件。有没有一种方法可以让我拥有相同的搜索栏组件,但有一个我可以传递的属性,以便它知道要搜索哪些数据。我的搜索组件是<SearchBar type="PASS THIS VALUE" />,它被渲染了:
import React, { Component } from 'react';
class SearchBar extends Component {
render () {
function handleClick(e) {
e.preventDefault();
console.log("Clicked!!!");
}
return (
<div className="row main-search">
<div className="column">
<form action="">
<fieldset>
<label htmlFor="search">
<input type="text" placeholder="Start typing..." id="search-box" />
</label>
</fieldset>
</form>
</div>
<div className="column">
<div className="float-right"><button className="add-new" onClick={handleClick}>Add New</button></div>
</div>
</div>
)
}
}
export default SearchBar;
如果这不可能,是否有办法让 searchBar 知道用户在哪个页面上并知道要搜索哪些数据?
更新:
我正在使用路由器元素,searchBar 组件位于父 App.js 内。我正在使用这样的路由器:
<SearchBar />
<Route
exact path="/" children={({ match, ...rest }) => (
<TransitionGroup component={firstChild}>
{match && <TourList {...rest} />}
</TransitionGroup>
)}/>
【问题讨论】:
-
你在用路由器吗?可以分享
SearchBar的父组件吗? -
我使用的是 app.js 主文件中的
react-router-dom -
您可以将路由器 props 传递给您的
SearchBar以便能够访问当前的路由 props 或使用像 redux 或 mobx 之类的 HOC 来处理全局应用程序状态,以使您的组件之间的通信更容易.
标签: reactjs search components