React使用Hooks实现单选按钮切换表单显隐功能失效求解
问题根源
你声明的toggle状态初始为布尔类型,但在Radio的onChange回调中给settoggle传入了对象格式的值{ toggle: !toggle },导致状态类型错乱:
- 初始值
toggle = false(布尔假,表单隐藏) - 第一次点击时,你传入对象
{ toggle: true },toggle状态变为对象,而对象在{toggle ? <Form /> : null}的条件判断中恒为真,表单正常显示 - 第二次点击时,对对象类型的
toggle取反得到false,又传入新对象{ toggle: false },toggle依然是对象,条件判断还是为真,所以表单无法隐藏
修复方案
直接给settoggle传入布尔值即可,不需要包裹对象:
将Radio组件的onChange回调修改为:
onChange={() => settoggle(!toggle)}
修正后完整代码
import { useState } from 'react'; const WelcomeTab = () => { const [toggle, settoggle] = useState(false); return ( <React.Fragment> <Tab.Pane style={{ borderRadius: '7px', padding: '30px', }} attached={false} > <Grid> <Grid.Row> <Grid.Column floated="left" width={8}> <Header style={{ fontSize: '18px', fontFamily: 'Nunito-Regular', color: '#4F4F4F', }} > Welcome Screen </Header> </Grid.Column> <Grid.Column floated="right" width={4}> <Header as="h4" style={{ display: 'flex', justifyContent: 'space-around', marginLeft: '30px', }} > Customize <Radio toggle onChange={() => settoggle(!toggle)} /> </Header> </Grid.Column> </Grid.Row> </Grid> {toggle ? ( <Form style={{ paddingTop: '20px' }}> <Form.Field> <label style={lableStyle}>Title</label> <input style={{ marginBottom: '20px' }} /> <label style={lableStyle}>Message</label> <TextArea /> </Form.Field> </Form> ) : null} </Tab.Pane> </React.Fragment> ); }; const lableStyle = { fontFamily: 'Nunito-Regular', fontWeight: 400, color: '#4F4F4F', fontSize: '15px', display: 'inline-block', marginBottom: '10px', }; export default WelcomeTab;
内容的提问来源于stack exchange,提问作者Pruthvi mohan
相关产品推荐
相关产品推荐

