如何根据React JS中的复选框状态(选中 – 未选中)显示/隐藏div,我对React很新,我知道如何在
jquery中执行此操作但是在React上是另一种方法.提前致谢.
EDITED
想要使用className =“showhidediv”显示/隐藏div,如果选中了复选框.
import React from 'react'; import ReactDOM from 'react-dom'; import DocumentTitle from 'react-document-title'; import {UserProfileForm }from 'react-stormpath'; import Calendar from '../components/Calendar' export default class PatientPage extends React.Component { render() { return ( <DocumentTitle title={`PvSafety - D Patient`}> <div className="container-fluid"> <div className="row"> <div className="col-xs-12"> <h3>D Patient</h3> <hr /> </div> </div> <div className="container-fluid" id = "dpatientBlock"> <div className="row"> <div className="panel panel-default"> <div className="panel-heading"> <form className="form-inline"> <div className="checkBox"> <label> <input type="checkBox" />Pregnant </label> </div> </form> </div> </div> </div> <div className="row"> <form className="form-horizontal" role="form"> <div className="col-md-6"> <div className="form-group"> <label id="id_label_patientnameinitials" htmlFor="id_field_patientnameinitials" className="col-md-6 control-label2"> <span className="e2bcode" id="E2BCodes" >D.1</span>Patient (name or initials) </label> <div className="col-md-4" > <input className="form-control showhidediv" tabIndex="1" id="id_field_patientnameinitials" type="text" placeholder="maskable" /> </div> </div> <div className="form-group"> <label id="id_label_gpmedical" htmlFor="id_field_gpmedical" className="col-md-6 control-label2"> <span className="e2bcode" id="E2BCodes">D.1.1.1</span>GP Medical </label> <div className="col-md-4" > <input className="form-control" tabIndex="1" id="id_field_gpmedical" type="text" placeholder="maskable" /> </div> </div> <div className="form-group"> <label id="id_label_specialist" htmlFor="id_field_specialist" className="col-md-6 control-label2"> <span className="e2bcode" id="E2BCodes">D.1.1.2</span>Specialist </label> <div className="col-md-4" > <input className="form-control" tabIndex="1" id="id_field_specialist" type="text" placeholder="maskable"/> </div> </div>
解决方法
你可以这样做:
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 content = this.state.checked ? <div> Content </div> : null; return <div> <div> <label>Check</label> <input type="checkBox" checked={ this.state.checked } onChange={ this.handleChange } /> </div> { content } </div>; } }
此外,您可以使用CSS类(带有显示属性)来切换(display:none / block;)元素
render() { const hidden = this.state.checked ? '' : 'hidden'; return <div> <div> <label>Check</label> <input type="checkBox" checked={ this.state.checked } onChange={ this.handleChange } /> </div> <div className={ hidden }>1</div> <div className={ hidden }>2</div> <div className={ hidden }>3</div> <div className="bold">3</div> <div className={ hidden }>4</div> </div>; }