我有一个子组件:
import * as React from 'react';
import Select from 'react-select';
import { Link } from 'react-router-dom';
import { Button } from '../controls/Button/Button';
import { ISelectedItem } from '../../interfaces/ISelectedItem';
import * as service from "../../helpers/service";
export interface IProps{
onClickRender: (selectedItem: ISelectedItem) => void;
}
export interface IState {
customerData: ISelectedItem[];
selectedItem: ISelectedItem;
}
export class DropDownSearch extends React.Component<{}, IState>{
constructor(props: any) {
super(props);
this.state = ({
customerData: [],
selectedItem: { shortName: '', description: '' }
});
}
componentDidMount() {
service.fetchJson<ISelectedItem[]>("/api/customers")
.then((json) =>{
this.setState({
customerData: json
});
});
}
handleChange = (selectedItem: any) => {
this.setState({
selectedItem
});
}
render() {
const { selectedItem } = this.state;
const value = selectedItem && selectedItem;
return (
<div>
<Select
name="form-field-name"
value={this.state.selectedItem}
onChange={this.handleChange}
options={this.state.customerData}
labelKey="shortName"
/>
<Link to={{
path "/dashboard/" + this.state.selectedItem.shortName,
state: { detail : this.state.selectedItem }
}}>
<Button type="button" className="btn btn-primary" caption="Search" />
</Link>
</div>
);
}
}
我想将this.state.selectedItem
传递给Dashboard组件,该组件是以下父组件中Route配置的一部分:
import * as React from 'react';
import { Navbar } from './Navbar/Navbar';
import { ShortNameSelector } from './ShortNameSelector/ShortNameSelector';
import { Dashboard } from './Dashboard/Dashboard';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
export class App extends React.Component<{},{}>{
render(){
return(
<BrowserRouter>
<div className="container">
<Navbar />
<div className="col-lg-12">
<Switch>
<Route exact path="/" component={ShortNameSelector} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</div>
</div>
</BrowserRouter>
);
}
}
问题是我正在使用路由来切换我的子组件中按钮单击的组件。如何通过路由将this.state.selectedItem
对象从子项传递到仪表板组件(在父组件中显示)?
编辑:
所以我将state属性放在Link
标记内,并在Dashboard组件中引用它,如this.props.location.state.detail
,它可以正常工作。但是现在我想在新页面中打开该链接时将数据保留在该路由/仪表板组件中。我该怎么做呢?
答案 0 :(得分:0)
你可以这样使用
<Route path="/dashboard/:selectedItem" component={Dashboard} />
因此,您可以动态更新DOM URL中的所选项目,当您单击它时,可以使用“仪表板”组件中的“this.props.match.params.id”来访问该值。
答案 1 :(得分:0)
在React中通过Router在组件之间传递对象:我从我的项目中复制了代码片段,可能对您有用。
1)我使用NavLink,它应该将一个对象传递给我的InfoComponent
<NavLink to={{
pathname:
/菜单/ $ {props.data.code} ,
search: '',
state: { selectedMenu: props.data }
}} color="info" className="btn btn-info btn-success mx-4">Info</NavLink>
2)在我的路由器中,然后按如下所示在Router中接收传递的参数,并添加了控制台日志以更清楚地显示
<Route path="/menu/:item" render={(props) => {
console.log("::::::::: " + JSON.stringify(props.location.state.selectedMenu));
return (<InfoComponent selectedMenu={props.location.state.selectedMenu} />);
}} />