React使用MUI RadioGroup组件传值及onChange事件不触发问题求助
问题排查与修复方案
存在的问题
- 组件命名不规范:React自定义组件必须使用大驼峰命名,你代码里的
example、implment都是小写开头,React会将其识别为原生HTML标签,导致自定义组件逻辑不生效。 - props名称不匹配:子组件内给RadioGroup绑定的onChange事件是
this.props.handler,但父组件传递的时候用的是onChange属性,两者名称不一致导致处理函数没有正确传入子组件,事件无法触发。 - state初始化语法错误:类组件state初始化时,键值对使用冒号赋值,你写的
state = {value = "example1"}是错误语法,正确应为state = {value: "example1"}。 - this指向错误:父组件的handler是普通函数,触发时this不会指向组件实例,调用
this.setState会抛出报错,需要改成箭头函数绑定this。 - 值传递错误:父组件render内传递给子组件的value没有从
this.state取值,直接写value属于未定义变量,取不到正确的状态值。 - 冗余属性与导入导出语法错误:子组件RadioGroup重复声明了两次
aria-label属性;父组件导入子组件缺少路径,导出未写default。
修正后代码
封装的RadioGroup组件(文件名Example.js)
import React, { Component} from 'react'; import { FormControl, FormControlLabel, RadioGroup, Radio } from '@material-ui/core'; class Example extends Component{ render(){ return( <FormControl component="fieldset"> <RadioGroup value={this.props.value} onChange={this.props.handler} row aria-label="something" name="radio-something-group" > <FormControlLabel value="example1" control={<Radio />} label="Example 1" /> <FormControlLabel value="example2" control={<Radio />} label="Example 2" /> </RadioGroup> </FormControl> ); } } export default Example;
父业务组件(文件名Implement.js)
import React, { Component} from 'react'; // 替换为你实际的Example组件相对路径 import Example from './Example'; class Implement extends Component{ state = { value: "example1" } // 箭头函数绑定this指向 handler = (e) => { this.setState({ value: e.target.value }); } render(){ return( <Example value={this.state.value} handler={this.handler} /> ); } } export default Implement;
内容的提问来源于stack exchange,提问作者Abdulrazzak Alsssouki
相关产品推荐
相关产品推荐

