reactjs - 如何在反应材料标签中从父级更改标签
问题描述
我有一个像 FeedSwitcher 这样的组件,里面有两个标签
一个用于一般提要另一个仅用于当前用户的帖子
在开始的 FeedSwitcher 组件中,该值为 0,因此当前用户可以查看所有提要。
const FeedSwitcher = ({feed, posts, user }: FeedSwitcherProps) => {
const classes = useStyles();
const [value, setValue] = useState(0);
const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
setValue(newValue);
};
return (
<div className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
variant="fullWidth"
indicatorColor="primary"
textColor="primary"
aria-label="switcher tabs"
>
<Tab icon={<PeopleIcon />} aria-label="phone" />
<Tab icon={<PersonIcon />} aria-label="favorite" />
</Tabs>
<TabPanel value={value} index={0}>
<Feed feed={feed} />
</TabPanel>
<TabPanel value={value} index={1}>
<Posts posts={posts} user={user} />
</TabPanel>
</div>
);
};
当前用户发新帖后
(表单在父组件中)
我想显示索引为 1 的选项卡
如何从父级设置值?
我应该使用 redux 状态还是有其他直接和更简单的方法?
解决方案
状态需要在父组件中。
您可以为子组件提供值,并向其传递一个函数参数,就像onValueChange
它可以用来触发父状态的更新一样。
// in parent
const [feedSwitcherValue, setFeedSwitcherValue] = useState(0);
return (
<FeedSwitcher
feed={feed}
posts={posts}
user={user}
value={feedSwitcherValue}
onValueChange={value => setFeedSwitcherValue(value)}
/>
);
// child
const FeedSwitcher = ({feed, posts, user, value, onValueChange }: FeedSwitcherProps) => {
const classes = useStyles();
const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
onValueChange(newValue);
};
return (
<div className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
variant="fullWidth"
indicatorColor="primary"
textColor="primary"
aria-label="switcher tabs"
>
<Tab icon={<PeopleIcon />} aria-label="phone" />
<Tab icon={<PersonIcon />} aria-label="favorite" />
</Tabs>
<TabPanel value={value} index={0}>
<Feed feed={feed} />
</TabPanel>
<TabPanel value={value} index={1}>
<Posts posts={posts} user={user} />
</TabPanel>
</div>
);
};
推荐阅读
- bazel - Monorepo 与多个连接的 Bazel 工作区 - 是否有任何“陷阱”需要考虑?
- dependency-injection - blazor wasm 如何从 di 注入自定义类
- java - jar 未正确创建 mvn relase
- python - 如何使用 ctypes 从 Python 创建 C 结构?
- json - Swift/JSONEncoder:包含嵌套原始 JSON 对象文字的编码类
- c - 运行程序后imac死机
- python - 从网站提取数据时如何绕过验证码。我从 https://jp.indeed.com/ 中提取
- sensors - ESP32 模数 ADC
- html - 将鼠标悬停在我的卡片上并不能覆盖完整的卡片
- java - 如何在 DynamoDB 中使用包含函数和 DynamoDBMapper Java?