0

我的单选按钮不可点击。这是我的组件:为什么我的单选按钮不可点击?

import React from 'react'; 
import { Form, Radio } from 'semantic-ui-react'; 
import PropTypes from 'prop-types'; 

const RadioButton = ({ name, label, className, value, onClick, checked, defaultValue }) => (
    <Form.Field> 
    <Radio type="radio" label={label} defaultValue={defaultValue} value={value} name={name} className={className} onClick={onClick} checked={checked} /> 
    </Form.Field> 
); 

RadioButton.propTypes = { 
    name: PropTypes.string.isRequired, 
    label: PropTypes.string.isRequired, 
    className: PropTypes.string, 
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(undefined)]), 
    defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(undefined)]), 
    onClick: PropTypes.oneOfType([PropTypes.func, PropTypes.instanceOf(undefined)]), 
    checked: PropTypes.bool, 
}; 

RadioButton.defaultProps = { 
    className: '', 
    value: undefined, 
    defaultValue: undefined, 
    onClick: null, 
    checked: false, 
}; 

export default RadioButton; 

我似乎无法理解为什么它不工作。有人有主意吗?

回答

2

您正在永久性地将checked prop设置为false,因此该复选框从不会更改已检查状态。为了使其工作,您需要通过React控制它的检查状态并管理组件中的状态(因此它不能成为无状态的功能组件)。这里有一个简单的例子:

class RadioButton extends React.Component { 
    //you can statically set propTypes and defaultProps here if you prefer 

    constructor(props) { 
    super(props); 
    this.handleClick = this.handleClick.bind(this); 
    this.state = { 
     checked: false 
    }; 
    } 

    handleClick() { 
    this.setState(prevState => ({ //ensure correct previous state when async call is batched 
     checked: !prevState.checked 
    })); 
    this.props.onClick && this.props.onClick(); //only execute if exists 
    } 

    render() { 
    return (
     <Form.Field> 
     <Radio {...this.props} onClick={this.handleClick} checked={this.state.checked} /> //{...this.props} passes props to Radio passed to RadioButton 
     </Form.Field> 
    ); 
    } 
} 

这将使用状态和管理检查和取消选中单选按钮。这支checked道具也不再需要了。

一个很好的经验法则是问问你自己,如果组件应该是互动或改变。如果是,那么它必须有内部状态。在这种情况下,必须检查和取消选中按钮,这两个状态为。因此你必须管理内部状态。

相关问题