react如何移除css属性,详解react的两种动态改变css样式的方法

本文介绍了两种在React中实现动态CSS的方法:通过动态添加class和动态设置style属性。这两种方式均可实现元素的显示与隐藏,并对比了它们的适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种:动态添加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 (

{/*动态添加一个class来改变样式*/}

你是我的唯一

点击隐藏

点击显示

)

}

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 (

{/*动态添加一个style来改变样式*/}

你是我的唯一

点击隐藏2

点击显示2

)

}

handleshow2() {

this.setState({

display2:true

})

}

handlehide2() {

this.setState({

display2:false

})

}

}

export default Demo;

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值