Reactjs:获取单选按钮的值

Reactjs:获取单选按钮的值,reactjs,Reactjs,我正在开发一个简单的民意调查,以此作为我的方法来提高我的反应能力。到目前为止,我已经得出以下结论: //App.js import React, { Component } from 'react'; import './App.css'; const PollOption = ({options}) => { return ( <div className="pollOption"> {options.map((choice, index) =>

我正在开发一个简单的民意调查,以此作为我的方法来提高我的反应能力。到目前为止,我已经得出以下结论:

//App.js
import React, { Component } from 'react';
import './App.css';

const PollOption = ({options}) => {


return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
        <input type="radio" 
                name="vote" 
                value={choice.value} 
                key={index}
                defaultChecked={choice.value}
                onChange={() => this.props.onChange()}/>
                {choice.text}
        </label>
      ))}  
    </div>
   );
};



class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: ''}
  }

  handleClick(){
    console.log('button clicked');
  }

  handleOnChange(){
    console.log('foo');
  }

  render(){
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption 
          options={this.props.model.choices}
          onChange={() => this.handleOnChange()}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
      </div>
    );
  }
}


    export default OpinionPoll;

    //index.js
    var json = {
            question: 'Do you support cookies in cakes?',
            choices:
            [
               {text: "Yes", value: 1},
               {text: "No", value: 2} 
            ]
        }
    const root = document.getElementById("root");
    render(<OpinionPoll model ={json} />, root)
//App.js
从“React”导入React,{Component};
导入“/App.css”;
常量PollOption=({options})=>{
返回(
{options.map((选项,索引)=>(
this.props.onChange()}/>
{choice.text}
))}  
);
};
类OpinionPoll扩展组件{
建造师(道具){
超级(道具);
this.state={selectedOption:'}
}
handleClick(){
log(“单击按钮”);
}
改变{
console.log('foo');
}
render(){
返回(
{this.props.model.question}
this.handleOnChange()}/>
这个.handleClick()}>投票!
);
}
}
导出默认的OpinionPoll;
//index.js
var json={
问题:“你支持蛋糕中的饼干吗?”,
选择:
[
{文本:“是”,值:1},
{文本:“否”,值:2}
]
}
const root=document.getElementById(“根”);
渲染(,根)

我想在单击按钮时获取单选按钮的值。

PollOption是一个功能组件,因此
关键字不可访问,因此
onChange={()=>this.props.onChange()}
不起作用。您还需要将所选值传递给父级

正如@RickyJolly在评论中提到的,要触发
onChange
,您需要选中
属性

const PollOption = ({options, onChange, selectedValue}) => {
  return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
        <input type="radio" 
                name="vote" 
                value={choice.value} 
                key={index}
                checked={selectedValue === choice.value}
                onChange={(e) => onChange(e.target.value)}/>
                {choice.text}
        </label>
      ))}  
    </div>
   );
};

class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: ''}
  }

  handleClick(){
    console.log('button clicked');
  }

  handleOnChange(val){
    console.log('foo', val);
  }

  render(){
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption 
          options={this.props.model.choices}
          onChange={(val) => this.handleOnChange(val)}
          selectedValue={this.state.selectedOption}
       />

        <button onClick={() => this.handleClick()}>Vote!</button>
      </div>
    );
  }
}
constpollpoption=({options,onChange,selectedValue})=>{
返回(
{options.map((选项,索引)=>(
onChange(e.target.value)}/>
{choice.text}
))}  
);
};
类OpinionPoll扩展组件{
建造师(道具){
超级(道具);
this.state={selectedOption:'}
}
handleClick(){
log(“单击按钮”);
}
手动更改(val){
console.log('foo',val);
}
render(){
返回(
{this.props.model.question}
这个.handleOnChange(val)}
selectedValue={this.state.selectedOption}
/>
这个.handleClick()}>投票!
);
}
}

只需对@Shubham Khatri答案稍作修改,即可添加
选中的属性和选定状态。此处演示:

const json={
问题:“你支持蛋糕中的饼干吗?”,
选择:
[
{文本:'Yes',值:'1'},
{文本:'No',值:'2'}
]
}
constpollpoption=({options,selected,onChange})=>{
返回(
{options.map((选项,索引)=>(
{choice.text}
))}
);
};
类opinion波尔扩展了React.Component{
建造师(道具){
超级(道具);
this.state={selectedOption:'}
}
handleClick(){
console.log('submitted option',this.state.selectedOption);
}
更改(e){
console.log('selected option',例如target.value);
this.setState({selectedOption:e.target.value});
}
render(){
返回(
{this.props.model.question}
这是(e)}
selected={this.state.selectedOption}/>
这个.handleClick()}>投票!
);
}
}
render(,document.getElementById('root'));

回答很好,但有一个小问题是,
onChange
事件不会触发,因为收音机没有更改的checked属性,因此它不会注册更改。谢谢,以前没有太多注意它。当选中单选按钮时,我可以在控制台中看到状态,但单选按钮没有被选中,这是为什么?请注意,我将json选项值更改为字符串。元素值将转换为字符串。因此,如果没有该更改,您的
checked={selected==choice.value}
将比较
'1'==1
,这是错误的。您可以使用双等于,如
selected==choice.value
,但最好使用
selected==choice.value.toString()
注意:将索引设置为键是一种反模式!并导致不可预测的结果
const json = {
  question: 'Do you support cookies in cakes?',
  choices:
  [
    { text: 'Yes', value: '1' },
    { text: 'No', value: '2' }
  ]
}

const PollOption = ({ options, selected, onChange }) => {
  return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
          <input type="radio"
            name="vote"
            value={choice.value}
            key={index}
            checked={selected === choice.value}
            onChange={onChange} />
          {choice.text}
        </label>
      ))}
    </div>
  );
};

class OpinionPoll extends React.Component {
  constructor(props) {
    super(props);
    this.state = { selectedOption: '' }
  }

  handleClick() {
    console.log('submitted option', this.state.selectedOption);
  }

  handleOnChange(e) {
    console.log('selected option', e.target.value);
    this.setState({ selectedOption: e.target.value});
  }

  render() {
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption
          options={this.props.model.choices}
          onChange={(e) => this.handleOnChange(e)}
          selected={this.state.selectedOption} />
        <button onClick={() => this.handleClick()}>Vote!</button>
      </div>
    );
  }
}

render(<OpinionPoll model={json} />, document.getElementById('root'));