• 技术文章 >web前端 >前端问答

    react 怎么改变css样式

    藏色散人藏色散人2022-12-30 10:02:53原创126
    react改变css样式的方法:1、动态添加一个class来改变样式,代码如“<p className={this.state.display?"active":"active1"}></p>”;2、动态添加一个style来改变样式,代码如“<p style={display2}></p>”。

    本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

    react 怎么改变css样式?

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

    第一种:动态添加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视频教程

    以上就是react 怎么改变css样式的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:css React
    上一篇:react native是框架吗 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • react怎么动态增加节点• react中modal不生效怎么办• react-native 运行不了怎么办• react怎么删除eslint
    1/1

    PHP中文网