Friday, 4 August 2017

javascript - Radio Input onChange only fires once?



I have a simple task I'm trying to accomplish: Fire a function whenever a radio button is toggled between its group.




class App extends Component {
onButtonClick() {
console.log('something was clicked!')
}

return (


type="checkbox"
onChange={this.onButtonClick.bind(this)}
/>
type="radio"
value="yes"
name="answer"
onChange={this.onButtonClick.bind(this)}

/>
type="radio"
value="no"
name="answer"
onChange={this.onButtonClick.bind(this)}
/>

)
}



The button and checkbox work just fine. If you click on it, it fires the function multiple times. The radio buttons fire once and then stop.



It's almost as if ReactJS stops watching for the onChange for radio buttons for some reason. Any help would be greatly appreciated. Thank you!



UPDATE



It seems like it works properly in https://codesandbox.io/s/rGMGzJNL, but is not working properly in my local environment which is utterly perplexing. Will update if I figure out what is going on, but would appreciate any guidance if anyone has run into this before!


Answer




You need to set checked property on each radio and save radio status in state.



class App extends Component {
state = {
radio: 'yes',
}

onButtonClick() {
console.log("something was clicked!");
}


onRadioChange(value) {
console.log("radio change");
this.setState({
radio: value,
})
}

render() {
return (



this.onButtonClick()} />
type="radio"
value="yes"
name="answer"
checked={this.state.radio === 'yes'}

onChange={(e) => this.onRadioChange('yes')}
/>
type="radio"
value="no"
name="answer"
checked={this.state.radio === 'no'}
onChange={(e) => this.onRadioChange('no')}
/>


);
}
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...