react入坑(三)选中未选中

mac2024-08-06  57

// import React from 'react'; // import ReactDOM from 'react-dom'; // import './index.css'; // import App from './App'; // import * as serviceWorker from './serviceWorker'; // ReactDOM.render(<App />, document.getElementById('root')); // // If you want your app to work offline and load faster, you can change // // unregister() to register() below. Note this comes with some pitfalls. // // Learn more about service workers: https://bit.ly/CRA-PWA // serviceWorker.unregister(); import React from 'react'; import ReactDOM from 'react-dom'; class CheckBox extends React.Component { state = { checked: false // 默认没有选中 }; // 交替(选中/没有选中)的状态 onClickCheckbox() { this.setState(prevState => { return { checked: !prevState.checked }; }); } render() { const checkboxClassArr = ['ui-checkbox']; // 如果选中,就添加一个 checked class 来给 css 做样式 if(this.state.checked) { checkboxClassArr.push('checked'); } // 组合最后的 class 结果 const checkboxClass = checkboxClassArr.join(' '); return ( <div onClick={this.onClickCheckbox.bind(this)}> {/* 这里模拟图标 */} <span className={checkboxClass}> <i className="icon-checkbox"></i> </span> {/* 这里模拟图标内容 */} <span>{this.state.checked ? '选中' : '没有选中'}</span> </div> ); } } ReactDOM.render( <CheckBox />, document.getElementById('root') );
最新回复(0)