React知识点:关于className处理

·  阅读 2026

react原生动态添加多个className会报错

var nwdbtn = "btn"
var nwdbtnLg = "btn-lg"
return (
    <button className={nwdbtn nwdbtnLg}>button</button>
)复制代码



解决方案classname库 

从一个极其简单的button组件看如何动态传入class

button组件

import React, {PureComponent} from "react"

import classNames from 'classnames';

class Button extends React.Component {
    constructor(props) {
        super(props)
    }
    componentDidMount() {

    }
    render() {
        const {
            type,
            size
        } = this.props;

        console.log(this.props)
        console.log(size)
        console.log(type)
        let sizeCls = '';
        switch (size) {
            case 'large':
                sizeCls = 'lg';
                break;
            case 'small':
                sizeCls = 'sm';
                break;
            default:
                break;
        }
        let btnClass = classNames("btn",{
            [`btn-${sizeCls}`]: sizeCls,
            [`btn-${type}`]: type
        });

        return (
            <button className={btnClass}>button</button>
        )
    }
}


export default Button;复制代码

引用button组件

import React, {PureComponent} from "react"
import Button from "component/button"
class NwdPage extends React.Component {
    constructor(props){
        super(props)
    }
    componentDidMount() {
        var _this = this;
    }
    render () {
        return (
            <div><Button size="small" type="primary"></Button></div>
        )
    }
}
export default NwdPage复制代码




分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改