如何使用react获取单选按钮的检查值

时间:2018-12-12 03:36:58

标签: reactjs radio-button

我在组件单选按钮下方

qtp102185114-154-acceptor-2@6275fad4-ServerConnector@6a3aa688{HTTP/1.1}{0.0.0.0:8080} - priority:5 - threadId:0x00007f78a6e1c000 - nativeId:0x84 - state:BLOCKED
stackTrace:
java.lang.Thread.State: BLOCKED (on object monitor)
at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:234)
- waiting to lock <0x00000000a049f430> (a java.lang.Object)
at org.eclipse.jetty.server.ServerConnector.accept(ServerConnector.java:377)
at org.eclipse.jetty.server.AbstractConnector$Acceptor.run(AbstractConnector.java:500)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None

我将此组件用作

import React from 'react';
import PropTypes from 'prop-types';


export default class RadioButton extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange = (event) => {
        this.props.handleChange(event);
    }
    render() {
        return (
            <div>           
            <input type="radio" name="measureValue" value={this.props.value} onChange={this.handleChange} checked={true}/>
            <label>{this.props.value}</label>
            </div>

        );
    }
}

现在,由于handleChnage不是函数,我得到了错误。

2 个答案:

答案 0 :(得分:1)

要获取选中的值,请使用event.target.checked而不是event.target.value,以便:

 handleRadioSelect = (event) =>{
    this.setState({
        radioChecked : event.target.checked
     })
 } 

出现错误,是因为您需要对this.handleCheck使用箭头功能(以便您可以传递事件道具),以便:

onChange={e => this.handleCheck(e)}

在这种情况下,您无需再绑定它,只需对handleCheck使用常规功能即可,

handleChange(event) {
    this.props.handleChange(event);
}

这是我通常的处理方式,希望对您有所帮助!

答案 1 :(得分:0)

handleChange = (event) => {
   let target = event.target;
   let name = target.name;
   let value = target.type === 'checkbox' ? target.checked : target.value;
   this.setState({
       [name] : value
   })
}

希望这会有所帮助