I'm trying to create a form in one of my React components. Input and Textarea works fine, but I can't even get the checkbox or radio button to show up. Neither render, but the labels for them do. I followed the tutorial on reactjs.org, but with no luck.
Am I missing something?
Here's what I have:
export default class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked: true
};
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
}
handleCheckboxChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<div>
<form>
<label>
<input name="isChecked"
type="checkbox"
checked={this.state.isChecked}
onChange={this.handleCheckboxChange}/>
ONE</label>
<label>
<input type="checkbox"
name="isChecked"
checked={this.state.isChecked}
onChange={this.handleCheckboxChange} />
TWO</label>
</form>
</div>
);
}
}
答案 0 :(得分:1)
(Apologies, as I do not have enough reputation to post a comment)
Your question is not clear, but I assume the issue you are facing is that you component is not rendering on screen.
There seems to be no problem with your code and the check boxes are showing up correctly. Check out a JSFiddle I tried out.
HTML
<script src="https://reactjs.org/js/jsfiddle-integration.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Javascript 1.7
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked: true
};
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
}
handleCheckboxChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<div>
<form>
<label>
<input name="isChecked"
type="checkbox"
checked={this.state.isChecked}
onChange={this.handleCheckboxChange}/>
ONE</label>
<label>
<input type="checkbox"
name="isChecked"
checked={this.state.isChecked}
onChange={this.handleCheckboxChange} />
TWO</label>
</form>
</div>
);
}
}
class HelloWidget extends React.Component{
constructor(props) {
super(props);
}
render() {
return <div className="widget">
<Example/>
</div>;
}
}
React.render(<HelloWidget />, document.getElementById('container'));
JSFiddle link to check the output