【发布时间】:2021-06-23 18:31:51
【问题描述】:
我使用了 material-UI 的 tabs 元素,但我从 props 中收到了 tabs 本身。 第一个值为 0 的选项卡,我想被选中。
这是我的代码:
import React, { useContext } from 'react';
import { ChannelContext } from '../context/channelContext'
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
export default function Channels(props) {
let channelsList = []
props.channels.forEach((elem,i) => {
channelsList.push( <Tab key={i} label={elem.channel_name} value={elem.server_id-1} />)
})
const [, setchannelBanner] = useContext(ChannelContext)
const [channelId, setChannelId] = React.useState(0);
const handleChange = (event, newValue) => {
setChannelId(newValue)
setchannelBanner(props.channels[newValue].bg_image);
};
return (
<AppBar position="static" color="inherit" elevation={0}>
<Tabs
value={channelId}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
aria-label="scrollable auto tabs" className="tabs">
{channelsList}
</Tabs>
</AppBar>
);
}
我在浏览器控制台上收到此错误:
"Material-UI: The value provided to the Tabs component is invalid.
None of the Tabs' children match with `0`.
You can provide one of the following values: NaN."
如果我将 React.useState(0) 更改为 React.useState(false) 或 React.useState(NaN),则错误消失但未选择第一个选项卡。 我知道这是因为主 Tabs 元素在内部 tabs 数组之前加载。 您建议如何解决?
【问题讨论】:
-
你能分享这段代码的代码沙箱链接吗?在那里编辑/调试东西会容易得多。
标签: reactjs react-hooks material-ui