近期正在逐步摸索学习React的用法,尝试着写几个通用型的组件,总体项目仍是根据webpack+react+css-medules构建,
项目代码 https://github.com/sunrun93/react-custom-components
启动项目:css
git clone git@github.com:sunrun93/react-blog-app.git npm i npm start
启动项目后,如若发现本地css未生效,请在node_modules\react-scripts\config\webpack.config.dev.js和node_modules\react-scripts\config\webpack.config.prod.js找到对应的css-loader, 在其options中添加以下两项(modules,localIdentName):node
loader: require.resolve('css-loader'), options: { modules: true, localIdentName: '[name]__[local]__[hash:base64:5]' }
主要组件包括:react
let options = [ { id: '1', label: 'Option-A', value: 'Option-A' }, { id: '2', label: 'Option-B', value: 'Option-B' }, { id: '3', label: 'Option-C', value: 'Option-C' }, { id: '4', label: 'Option-D', value: 'Option-D' } ]; <SearchBox options={options}/> //显示label
<input type="checkbox" checked={this.state.isCheck} className={this.state.isCheck?styles.greenDotRight:styles.greenDotLeft}/> <label></label>
input[type='checkbox'] { visibility:hidden; position:absolute; } .greenDotLeft+label{ width:30px; height: 30px; border-radius: 15px; background-color:lightgray; display: inline-block; position: absolute; left: 0; } .greenDotRight+label{ width: 30px; height: 30px; border-radius: 15px; background-color: lawngreen; display: inline-block; position: absolute; right:0; }
调用方式以下:webpack
<ToggleBtn isChecked={isChecked} onClick={toggleEvent}/> //onClick触发想要调用的方法,接受一个参数拿到当前的状态,isChecked可定义初始化的值
首先咱们考虑一下两点:ios
ReactDOM.unstable_renderSubtreeIntoContainer
方法将其插入到DOM的根节点,结构以下(Layer层为遮罩层,Dialog为咱们实际构造的组件):<Layer> <Dialog> /* customer defined dialog content */ </Dialog> </Layer>
Layer层的具体实现以下,具体请查看git
class Layer extends React.Component { constructor(props) { super(props); } componentDidMount() { this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { this.removeLayer(); } renderLayer() { if (!this.props.open) { this.removeLayer() } else { if (!this.layer) { this.layer = document.createElement("div"); this.layer.className = styles.layer; document.body.appendChild(this.layer);//首先将Layer节点添加到DOM中 } ReactDOM.unstable_renderSubtreeIntoContainer(this, this.props.children, this.layer); //而后经过unstable_renderSubtreeIntoContainer方法将其放到根结点下 } } removeLayer() { if (!this.layer) { return; } ReactDOM.unmountComponentAtNode(this.layer); document.body.removeChild(this.layer); this.layer = null; } render() { return null; } }
具体实现方式:https://github.com/sunrun93/react-custom-componentsgithub