第一种:动态添加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> {/*动态添加一个class来改变样式*/} <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> {/*动态添加一个style来改变样式*/} <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样式内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!
您可能感兴趣的文章:
- React使用emotion写css代码
- 基于react项目打包css引用路径错误解决方案
- react使用CSS实现react动画功能示例
- react中使用css的7中方式(最全总结)
- 在Create React App中使用CSS Modules的方法示例
- 在create-react-app中使用css modules的示例代码
- 详解使用create-react-app添加css modules、sasss和antd
- ReactJs设置css样式的方法
- 如何用react优雅的书写CSS
本文由 华域联盟 原创撰写:华域联盟 » 详解react的两种动态改变css样式的方法
转载请保留出处和原文链接:https://www.cnhackhy.com/57292.htm