我有这段代码
class Component extends React.Component {
constructor() {
super();
this.state = { checked: false };
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked
})
}
render() {
const hidden_chk1 = this.state.checked ? 'hidden' : '';
const hidden_chk2 = this.state.checked ? 'hidden' : '';
return <div>
<div>
<label>Check 1</label>
<input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
<label>Check 2</label>
<input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked } onChange={ this.handleChange } />
</div>
<div className={ hidden_chk1 }>show hide div with check 1</div>
<div className={ hidden_chk2 }>show hide div with check 2</div>
</div>;
}
}
ReactDOM.render(
<Component />,
document.getElementById('container')
);
这是JSfiddle:https://jsfiddle.net/v5xsawn8/1/
我正在努力解决这个问题并且无法使其工作,复选框1必须仅控制div check 1 hidden_chk1而复选框2必须仅控制div checkbox2 hidden_chk2,它们必须是独立的,谢谢提前。
答案 0 :(得分:0)
最后我在这里工作的是代码:
JS
class Componente extends React.Component {
constructor(props) {
super(props);
this.state = { checked: false, checked2: false};
this.handleChange = this.handleChange.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked
})
}
handleChange2() {
this.setState({
checked2: !this.state.checked2
})
}
render() {
const togglecheck1 = this.state.checked ? 'hidden-check1' : '';
const togglecheck2 = this.state.checked2 ? 'hidden-check2' : '';
return <div>
<div>
<label>Check 1</label>
<input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
<label>Check 2</label>
<input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked2 } onChange={ this.handleChange2 } />
</div>
<div className={ togglecheck1 }>show hide div with check 1</div>
<div className={ togglecheck2 }>show hide div with check 2</div>
</div>;
}
}
ReactDOM.render(
<Componente />,
document.getElementById('container')
);
CSS
.hidden-check1 {
display: none;
}
.hidden-check2{
visibility: hidden;
}
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
in css =&gt; visibility:hidden隐藏div并保留空格和=&gt; display:none隐藏div而不保留空间。 这是codepen http://codepen.io/parlop/pen/EKmaWM ,谢谢。