【问题标题】:How to change style property on button onClick in React?如何在 React 中更改按钮 onClick 的样式属性?
【发布时间】:2019-05-02 15:16:08
【问题描述】:

我有一个要在单击按钮时隐藏的响应元素。

元素样式在构造函数中加载如下:

 constructor(props) {
super(props);
this.state = {
  display: 'block'
};
this.ElementStyle= {
  width: '100%',
  backgroundColor: '#F6F6F6',
  color: '#404040',
  padding: '8px 15px',
  boxSizing: 'content-box',
  position: 'fixed',
  bottom: '0',
  display: this.state.display
    }
  }

元素在它的 render() 中有一个按钮,它调用一个改变状态的函数,如下所示:

render()  {
  <button onClick={this.Method.bind(this)}>Click me </button>
}

还有 Method():

  Method() {
    this.setState({
      display: 'none'
    });
  }

然后我有这个:

  shouldComponentUpdate() {
    this.ElementStyle.display = this.state.display;
  }

不过这是在说:"TypeError: "display" is read-only"

【问题讨论】:

  • 在我当前的项目中,我在 componentDidMount() 方法中使用了 jquery 来完成此操作。但是,我已经看到了对此的建议,所以我也想看看对此的想法。
  • 如果你在 react 中使用 jquery(如果你没有包装非反应库)可能是你以错误的方式使用它。此任务有多种方法,最简单的方法是在 CSS 中定义两个类并切换 className(不依赖 jQuery)
  • @MosèRaguzzini 好吧,我没有导入 jquery 只是为了肯定的切换方法。但我明白你在说什么,我也使用 vanilla js 和 css 来完成这项任务。我的意思是,在组件状态中包含所有这些不同的东西会变得乏味。我对状态的看法是,它旨在跟踪用户输入数据。当您开始在状态中存储基本的 UI 功能时,我想这似乎有点过头了。我必须习惯这个概念,因为这显然是“正确”的方式。
  • 视情况而定.在 CSS/Styled-components/SASS/LESS 或类似中管理单个 css 肯定更好,并考虑到简单地使用类

标签: javascript html css reactjs


【解决方案1】:

只需将样式置于状态:

状态

this.state = {
  ElementStyle: {
  width: '100%',
  backgroundColor: '#F6F6F6',
  color: '#404040',
  padding: '8px 15px',
  boxSizing: 'content-box',
  position: 'fixed',
  bottom: '0',
  display: 'block
};

方法

 Method() {
    this.setState({
      ElementStyle: {
      ...this.state.ElementStyle,
      display: 'none'
      }
    });
  }

渲染

render()  {
  <button style={this.state.ElementStyle} onClick={this.Method.bind(this)}>Click me </button>
}

【讨论】:

  • 这是我经常遇到的问题。状态中应该包含什么?我开始这样做,我的状态对象开始在我的一个组件中变得非常混乱。这被认为是好的做法吗?
  • 从状态操作 CSS 是个坏主意。无论状态如何,display 属性都会始终呈现元素。所以,好的做法是根本不渲染元素是状态是假的。
  • @silencedogood 也许你需要重构那个组件。例如:
  • @AnandGhaywankar 你是对的,但不是出于正确的原因。在状态下操作样式不利于关注点分离,想象一下在每个组件中为每个元素添加整个 CSS 管理。这就是我使用 styled-components/css modules/plain css 的原因。另一种方法是使 css 由检查状态的方法返回。但实际上,这个任务的老式“两个 CSS 类方法”是最合适的。
  • @wakajawaka 也许是的。我在那里有惰性加载器状态,css,各种各样的东西。最后我用 jquery 来减少事情。我想重构肯定是最好的答案。不过,在某些情况下,如此多的模块化可能会令人讨厌。
【解决方案2】:

我要做的是设置组件的样式并将显示初始设置为无, 喜欢:

// css
.yoourclass {
 width: '100%',
  backgroundColor: '#F6F6F6',
  color: '#404040',
  padding: '8px 15px',
  boxSizing: 'content-box',
  position: 'fixed',
  bottom: '0',
  display: none
    }

}

//have a class that show display to block
.show {
  display: block;
}

然后在你的javascript中

// set your state to some display property 
this.state = {
   showHiddenElement: false
}

//then you can set state to display css like
const {showHiddenElement} = this.state;
this.setState({
  showHiddenElement: !showHiddenElement
})
// and in your component 
// apply the class bases on the state like
const toggle = this.state.showHiddenElement;
<yourelement className={`yoourclass ${toggle? 'show' : ''}`}

类似的东西,我希望这是有道理的,让我知道。这是一种不同的方法。

【讨论】:

    【解决方案3】:

    没有做错 react 有一个虚拟 dom,它是自动管理的,但是你正试图改变它的行为, 我认为你可以这样做:

    constructor(props) {
        super(props);
        this.state = {
           display: 'block'
        };
    }
    
    
    Method() {
       this.setState({
           display: 'none'
       });
    }
    
    
    render()  {
      <div>
         <div style={{display: this.state.display}} ></div>
         <button onClick={this.Method.bind(this)}>Click me </button>
      </div>
    }
    

    您也有多种选择,但这是最简单的方法。

    【讨论】:

      【解决方案4】:

      我不确定您为什么要尝试使用 style 属性设置样式,但我们通常是使用 css 类和 css 样式表来做到这一点的。在运行时我们修改类而不是元素样式。

      因此,对于您的情况,我们会将这种风格作为某个类,比如App.scss

      .class-to-be-applied {
          width: 100%;
          background-color: #F6F6F6;
          color: #404040;
          padding: 8px 15px;
          box-sizing: content-box;
          position: fixed;
          bottom: 0;
      
          .no-display {
              display: none;
          }
      }
      

      App.js

      import React, { Component }  from 'react';
      import classnames from 'classnames';
      import './App.scss';
      
      class MyComponent extends Component {
          constructor(props) {
              super(props);
              this.state = {
                  display: true
              };
          }
          handleButtonClick = () => {
              this.setState(({ display }) => ({display: !display}));
          }
          render()  {
              return (
                  <div>
                      <button onClick={this.handleButtonClick}>Click me </button>
                      <SomeComponent className={classnames('class-to-be-applied', {'no-display': !this.state.display})} />
                  </div>
              );
          }
      }
      

      做同样事情的其他方法和更优选的方法是根本不渲染它以避免插入到树本身中,如下图App.js

      import React, { Component }  from 'react';
      import classnames from 'classnames';
      import './App.scss';
      
      class MyComponent extends Component {
          constructor(props) {
              super(props);
              this.state = {
                  display: true
              };
          }
          handleButtonClick = () => {
              this.setState(({ display }) => ({display: !display}));
          }
      
          render()  {
              return (
                  <div>
                      <button onClick={this.handleButtonClick}>Click me </button>
                      { this.state.display && <SomeComponent className=class-to-be-applied' /> }
                  </div>
              );
          }
      }
      

      【讨论】:

        【解决方案5】:

        1) 将您的对象放入内联 CSS 中:-

        render() {
            return (
                <div>
                    <button onClick={ this.Method.bind(this) }>Click me </button>
                    <h1 style={{
                         width: '100%',
                         backgroundColor: '#F6F6F6',
                         color: '#404040',
                         padding: '8px 15px',
                         boxSizing: 'content-box',
                         position: 'fixed',
                         bottom: '0',
                         display:this.state.display
                    }}>About</h1>
                </div>
            )
        }
        

        2) 并删除这个 shouldComponentUpdate() 函数

         shouldComponentUpdate() {
        this.ElementStyle.display = this.state.display;
        }
        

        【讨论】:

          猜你喜欢
          • 2014-05-24
          • 2019-07-13
          • 1970-01-01
          • 2015-02-14
          • 2016-04-10
          • 1970-01-01
          • 1970-01-01
          • 2014-07-07
          • 1970-01-01
          相关资源
          最近更新 更多