简体   繁体   English

如何在React上的onClick按钮上更改样式属性?

[英]How to change style property on button onClick in React?

I have an element in react that I want to hide when I click a button. 当我点击一个按钮时,我有一个想要隐藏的反应元素。

The element styles are loaded at the constructor like this: 元素样式在构造函数中加载,如下所示:

 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
    }
  }

And the element has got a button inside it's render() calling a function that changes state like so: 元素里面有一个按钮,它的render()调用一个改变状态的函数:

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

And the Method(): 而Method():

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

And then I have this: 然后我有这个:

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

This however is saying: "TypeError: "display" is read-only" 然而,这说: "TypeError: "display" is read-only"

Simply Place your styles in state: 只需将您的样式置于状态:

State

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

Method 方法

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

Render 给予

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

no did wrong react has a virtual dom, and it's managed automatically, but you are trying to change its behavior, I think you can do it like this: 没有做错的反应有一个虚拟的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>
}

you also have several options too, but it is simplest way. 你也有几个选择,但这是最简单的方法。

What I would do is style your component and set the display initialy to none, like: 我要做的是为您的组件设置样式并将显示初始化设置为none,例如:

// 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;
}

Then in your javascript 然后在你的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' : ''}`}

Something like that, I hope this makes sense, let me know. 这样的事情,我希望这是有道理的,让我知道。 It is a different approach. 这是一种不同的方法。

I am not sure why you're trying to set style using style property, but how we usually do this is using css classes and css stylesheets. 我不确定你为什么要尝试使用style属性设置样式,但我们通常如何使用css类和css样式表。 And in runtime we modify classes instead of element styles. 在运行时,我们修改类而不是元素样式。

So, for your case, we would have that style as some class like in, let's say App.scss 所以,对于你的情况,我们会把这种风格作为一些类,比如说,让我们说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;
    }
}

and in App.js , 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>
        );
    }
}

Other way to do the same thing and more preferred way is to just not render it at all to avoid inserted into the tree itself, like below for App.js , 其他方式做同样的事情和更优选的方法是不要渲染它以避免插入树本身,如下面的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>
        );
    }
}

1) Put your object inside inline CSS :- 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) And remove this shouldComponentUpdate() function 2)并删除这个shouldComponentUpdate()函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM