gpt4 book ai didi

reactjs - Material UI Tab 将 props 传递给组件

转载 作者:行者123 更新时间:2023-12-02 16:24:45 25 4
gpt4 key购买 nike

我正在尝试将react-router与Material-UI V1选项卡集成,如this github issue , this stackoverflow post ,以及他们对我来说错误的答案。

据我了解,这就是你应该执行的方式:

import Tab from '@material-ui/core/Tab';
import Link from 'react-router-dom';
/* other code */
<Tab component={Link} to="/" value={'/'} key={'/'} label={'/'}/>

但是我收到错误[ts]属性“to”在类型上不存在...

我也尝试过:

<Tab component={() => <Link to='/' />} value={'/'} key={'/'}] label={'/'}/>

但在这种情况下,我的 Tab 组件根本不渲染。

想法?

最佳答案

问题的根源在于 Tab 类型是这样声明的:

declare const Tab: React.ComponentType<TabProps>;

TabProps 当然没有 to 属性。

要解决该问题,请声明一个名为 LinkTab 的新变量:

const LinkTab: React.ComponentType<TabProps & LinkProps> = Tab as React.ComponentType<TabProps & LinkProps>;

并像下面这样使用它:

<LinkTab icon={<ListIcon />} component={Link} to="/monitor" />

这应该可以正常编译。

带有导入的完整代码示例:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { MonitorContainer } from "Monitor/MonitorContainer";
import { HashRouter as Router, Route, Redirect, Switch, Link, LinkProps } from 'react-router-dom';
import { RemoteContainer } from "Remote/RemoteContainer";
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import { default as Tab, TabProps } from '@material-ui/core/Tab';
import ListIcon from '@material-ui/icons/ListAlt';
import RemoteControlIcon from '@material-ui/icons/SettingsRemote';
import './reset.css';
import './index.scss';
import '../assets/fonts/icons/flaticon.css';

const LinkTab: React.ComponentType<TabProps & LinkProps> = Tab as React.ComponentType<TabProps & LinkProps>;

export interface AppState {
value: number;
}

export class App extends React.Component<{}, AppState> {
constructor(props: Readonly<{}>) {
super(props);

this.state = {
value: 0,
};
}

handleChange = (event: any, value: any) => {
this.setState({ value });
};

render() {
const { value } = this.state;

return (
<div>
<AppBar position="static">
<Tabs value={value} onChange={this.handleChange} scrollable scrollButtons="off">
<LinkTab icon={<ListIcon />} component={Link} to="/monitor" />
<LinkTab icon={<RemoteControlIcon />} component={Link} to="/remote" />
</Tabs>
</AppBar>
</div>
)
}
};

ReactDOM.render(
<Router>
<div>
<App />
<Switch>
<Route exact path="/monitor" component={ MonitorContainer } />
<Route exact path="/remote" component={ RemoteContainer } />
<Redirect from="/" to="/monitor" />
</Switch>
</div>
</Router>,
document.getElementById("root")
);

关于reactjs - Material UI Tab 将 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com