React JS编译报错:render后提示缺少分号 组件无法正常渲染
问题根因
你混淆了React类组件和函数组件的语法规则,当前你写的是函数组件(用const AddContact = () => {}定义),却使用了仅类组件支持的render()方法、this.state、this.refs语法,编译器识别不了render(){的写法,才会误判为缺少分号。
需要修改的核心问题
- 函数组件不需要
render()方法包裹返回的JSX,直接return即可,删除代码里的render(){和对应的闭合花括号 - 函数组件没有
this指向,所有this.refs、this.state、this.setState写法全部无效,需要替换为函数组件对应的Hooks写法 - 你在
onValueChange方法中展开的contact变量是后续才定义的,会报变量未定义错误 - 没有声明错误提示对应的状态变量,验证逻辑无法正常存储错误信息
- 提交按钮没有先走验证逻辑,直接调用了新增接口
关键修改代码示例
// 顶部导入新增useRef import react, { useState, useRef } from "react" // 删除重复导入的react、删除没用的import { render } from "react-dom" const useStyle = makeStyles({ container: { width: '50%', margin: '5% 0 0 25%', '& > *': { marginTop: 20 } } }) const initialValues = { name: '', email: '', phone: '', location: '' } const AddContact = () => { const [contacts, setContact] = useState(initialValues); // 新增errors状态存储验证错误 const [errors, setErrors] = useState({}); const { name, email, phone, location } = contacts; const classes = useStyle(); const history = useHistory(); // 声明各个输入框的ref const fullnameRef = useRef(null); const emailRef = useRef(null); const contactRef = useRef(null); const locationRef = useRef(null); const regdateRef = useRef(null); const onValueChange = (e) => { // 替换contact为当前的contacts状态 setContact({ ...contacts, [e.target.name]: e.target.value }) } const [regdates, setValue] = React.useState(new Date()); let regdate= parseInt(regdates.getMonth()+1) + "/"+ regdates.getDate() + "/"+regdates.getFullYear(); const contact = {...contacts,regdate}; console.log(contact); console.log(regdate); const addContactDetails = async () => { // 先验证再提交 if(validate()){ await addContact(contact); history.push('./AllContact'); } } const validate = () => { let isValid = true; let name = ''; let email = ''; let contact = ''; let location = ''; let regDate = ''; // 替换this.refs为useRef的取值 let nameCheck = fullnameRef.current?.value || ''; let emailCheck = emailRef.current?.value || ''; let contactCheck = contactRef.current?.value || ''; let locationCheck = locationRef.current?.value || ''; let regDateCheck = regdateRef.current?.value || ''; // 这里保留你原有的验证规则代码即可,不需要修改判断逻辑 if (!isValid) { // 替换this.setState为setErrors setErrors({ nameError: name, emailError: email, contactError: contact, locationError: location, regDateError: regDate, }); return false; } // 验证通过清空错误 setErrors({}); return true; }; // 删除render(){,直接return JSX,所有this.state.errors替换为errors,所有ref="xxx"替换为ref={对应的ref变量} return ( <FormGroup className={classes.container}> <Typography variant="h4">Add Contact</Typography> <FormControl> <InputLabel>Full Name *</InputLabel> <Input onChange={(e) => onValueChange(e)} name='name' value={name} placeholder="Last Name, First Name Middle Initial" ref={fullnameRef} defaultValue="" required /> {errors['nameError'] ? ( <Alert color="danger"> <strong>{errors['nameError']}!</strong> </Alert> ) : null} </FormControl> <FormControl> <InputLabel>Email Address *</InputLabel> <Input onChange={(e) => onValueChange(e)} name='email' value={email} placeholder="example@email.com" ref={emailRef} required/> {errors['emailError'] ? ( <Alert color="danger"> <strong>{errors['emailError']}!</strong> </Alert> ) : null} </FormControl> <FormControl> <InputLabel>Contact Number *</InputLabel> <Input onChange={(e) => onValueChange(e)} name='phone' value={phone} placeholder="09XXXXXXXXX" ref={contactRef} required/> {errors['contactError'] ? ( <Alert color="danger"> <strong>{errors['contactError']}!</strong> </Alert> ) : null} </FormControl> <Box sx={{ minWidth: 120 }}> <InputLabel>Location *</InputLabel> <FormControl fullWidth> <Select required labelId="demo-simple-select-label" id="demo-simple-select" onChange={(e) => onValueChange(e)} value={location} label="location" name="location" ref={locationRef} > <MenuItem value="">Select Location</MenuItem> <MenuItem value="Manila">Manila</MenuItem> <MenuItem value="Cebu">Cebu</MenuItem> </Select> {errors['locationError'] ? ( <Alert color="danger"> <strong>{errors['locationError']}!</strong> </Alert> ) : null} </FormControl> </Box> <FormControl> <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker disableFuture label="Register Date*" views={['year', 'month', 'day']} value={regdates} name='regdate' ref={regdateRef} onChange={(newValue) => { setValue(newValue); }} renderInput={(params) => <TextField {...params} />} /> </LocalizationProvider> {errors['regDateError'] ? ( <Alert color="danger"> <strong>{errors['regDateError']}!</strong> </Alert> ) : null} </FormControl> <Button variant="contained" onClick={addContactDetails} color="primary">Add Contact</Button> </FormGroup> ) } export default AddContact
内容的提问来源于stack exchange,提问作者Keopta Gaming
相关产品推荐
相关产品推荐

