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

时间:2019-05-02 15:16:09

标签: javascript html css reactjs

当我单击按钮时,我有一个要隐藏的元素。

将元素样式加载到构造函数中,如下所示:

 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"

5 个答案:

答案 0 :(得分:3)

只需将样式置于状态:

状态

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

答案 1 :(得分:0)

没有错 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>
}

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

答案 2 :(得分:0)

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

// 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 :(得分:0)

我不确定为什么要尝试使用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>
        );
    }
}

答案 4 :(得分:0)

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

from bokeh.models import ColumnDataSource, FactorRange, RangeSlider, CustomJS
from bokeh.plotting import figure
from bokeh.layouts import column
import pandas as pd

output_file("grouped_customJS.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 3, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

df = pd.DataFrame.from_dict(data)

df=df.set_index('fruits').stack().reset_index()
df=df.rename(columns={'level_1':'year', 0:'value'})

# add year as int column for slider
df['year_int'] = df['year'].astype(int)
df=df.set_index(['fruits','year'])

cats = df.index.values

source = ColumnDataSource(
        data = {
            'categories': cats,
            'values': df['value'],
            'year': df['year_int']
        }
)

p = figure(
        x_range=FactorRange(*cats),
        plot_height=250,
        title="Fruit Counts by Year",
)

p.vbar(x='categories', top='values', width=0.9, source=source)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

slider = RangeSlider(
    start=df['year_int'].min(),
    end=df['year_int'].max(),
    step = 1,
    value = (df['year_int'].min(), df['year_int'].max()),
)

callback = CustomJS(args=dict(slider=slider, source=source, plt = p), code="""
    plt.x_range.factors = [];
    for (var i = 0; i < source.get_length(); i++){
        if (source.data['year'][i] >= slider.value[0] && source.data['year'][i] <= slider.value[1]){
            plt.x_range.factors.push(source.data['categories'][i]);
        }
    }
""")

slider.js_on_change('value', callback)
p.x_range.js_on_change('factors', callback)

show(column(p, slider))

2)并删除此 shouldComponentUpdate()函数

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