iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >详解react的两种动态改变css样式的方法
  • 615
分享到

详解react的两种动态改变css样式的方法

2024-04-02 19:04:59 615人浏览 安东尼
摘要

第一种:动态添加class,以点击按钮让文字显示隐藏为demo import React, { Component, Fragment } from 'react'; impor

第一种:动态添加class,以点击按钮让文字显示隐藏为demo


import React, { Component, Fragment } from 'react';
import './style.CSS';
class Demo extends Component{
    constructor(props) {
        super(props);
        this.state = {
            display: true
        }
        this.handleshow = this.handleshow.bind(this)
        this.handlehide = this.handlehide.bind(this)
    }
    render() {
        return (
            <Fragment>
                {}
                <p className={this.state.display?"active":"active1"}>你是我的唯一</p>
                <button onClick={this.handlehide}>点击隐藏</button>
                <button onClick={this.handleshow}>点击显示</button>
            </Fragment>
        )
    }
    handleshow() {
        this.setState({
            display:true
        })
    }
    handlehide() {
        this.setState({
            display:false
        })
    }
}
export default Demo;

css代码:


 .active{
      display: block;
  }
  .active1{
    display: none;
  }

第二种:动态添加一个style,以点击按钮让文字显示隐藏为demo


import React, { Component, Fragment } from 'react';
class Demo extends Component{
    constructor(props) {
        super(props);
        this.state = {
            display2: true
        }
        this.handleshow2 = this.handleshow2.bind(this)
        this.handlehide2 = this.handlehide2.bind(this)
    }
    render() {
        const display2 = {
            display:this.state.display2 ? 'block' : 'none'
        }
        return (
            <Fragment>
                 {}
                 <p style={display2}>你是我的唯一</p>
                <button onClick={this.handlehide2}>点击隐藏2</button>
                <button onClick={this.handleshow2}>点击显示2</button>
            </Fragment>
        )
    }
    handleshow2() {
        this.setState({
            display2:true
        })
    }
    handlehide2() {
        this.setState({
            display2:false
        })
    }
}
export default Demo;

总结:用class来改变css样式,可以写多个动态改变的css属性,看起不杂乱,而用style写的话,如果写多个css属性就会看起复杂。都是个人观点,不足请指出

到此这篇关于详解react的两种动态改变css样式的方法的文章就介绍到这了,更多相关react动态改变css样式内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解react的两种动态改变css样式的方法

本文链接: https://www.lsjlt.com/news/123488.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作