首页 > 解决方案 > 如何在反应材料标签中从父级更改标签

问题描述

我有一个像 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 状态还是有其他直接和更简单的方法?

标签: reactjsreact-material

解决方案


状态需要在父组件中。

您可以为子组件提供值,并向其传递一个函数参数,就像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>
  );
};

推荐阅读