题意:
在按钮点击时有条件地渲染三个组件中的一个(React)
问题背景:
I'm new to react and been struggling to figure out how to render the components inside the container depending on which button has been clicked.
我刚接触React,一直在努力弄明白如何根据点击了哪个按钮来渲染容器内的组件。
I've set the state to false, then on the button click set it to true then used a ternary operator to show or set the component to null but won't work when the next button is clicked because the state is already set to true.
我将状态设置为false
,然后在按钮点击时将其设置为true
,再使用三元运算符来显示组件或将组件设置为null
,但是当点击下一个按钮时不起作用,因为状态已经被设置为true
。
any help in the right direction would be appreciated :)
任何朝正确方向的帮助都会非常感激 :)
const AboutUs = () => {
const [VisDetails, setVisDetails] = useState(false);
return (
<Button>Personal Details</Button>
<Button>Bio</Button>
<Button>Qualifications</Button>
Container className={classes.container}>
<PersonalDetails />
<ProfileBio />
<ProfileQualifications />
</Container>
);
};
问题解决:
I think the best thing to do in this case is save the state depending on what content should be showing and then update that state on button click.
我认为在这种情况下,最好的做法是根据应该显示的内容保存状态,然后在按钮点击时更新该状态。
Something like this
像这样
const AboutUs = () => {
const [selected, setSelected] = useState(null); //Here goes the default value you want to show, or null if you want no render
return (
<>
<Button
onClick={() => {
setSelected("personaldetails");
}}
>
Personal Details
</Button>
<Button
onClick={() => {
setSelected("bio");
}}
>
Bio
</Button>
<Button
onClick={() => {
setSelected("qualif");
}}
>
Qualifications
</Button>
<Container className={classes.container}>
{selected == "personaldetails" ? <PersonalDetails /> : null}
{selected == "bio" ? <ProfileBio /> : null}
{selected == "qualif" ? <ProfileQualifications /> : null}
</Container>
</>
);
};
You could use a switch() but I like the inline if statement, easier to read.
你可以使用switch()
,但我更喜欢内联的if
语句,这样更容易阅读。