问题描述
我有一个像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>
);
};
(该表单位于父组件中)
如何设置父项的值?
我应该使用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>
);
};