代码之家  ›  专栏  ›  技术社区  ›  Ghoyos

如何使用reacts“onClick”更改样式。元素的背景颜色

  •  4
  • Ghoyos  · 技术社区  · 7 年前

    我最近一直在尝试react,想知道如何使用reacts“onClick”语法来更改元素的背景色。有关此问题的相关页面位于我的git hub帐户上,两者都是 App.js App.css .

    正如你所见;我已经到了这样一个地步,一旦你“点击”了包含文本的元素,你就可以“点击我”它调用函数boxClick()。但一旦运行box click中的代码,就会出现错误-> (imgurPic) . 现在,如果这是一个普通的js页面,我可以很容易地做到这一点,但我是新的反应。我想知道如何使这个函数正常工作,以及为什么当前的代码不工作。在我看来,当我使用文档时,我确实定义了“boxClickCss”。getElementsByClassName;这就是为什么我不理解这个错误。

    4 回复  |  直到 7 年前
        1
  •  10
  •   Sajith Edirisinghe    7 年前

    在React中,直接操作实际DOM是一种不好的做法,因为React更改首先应用于虚拟DOM,然后在实际DOM中只修改差异。此外,在调用函数时,DIV可能实际上不存在于真实的DOM中。

    通过阅读 official documentation .

    但是,对于您的问题,您需要使用 state 更改分区的颜色。下面是代码(仅包括修改的部分)

    class App extends Component {
    
      constructor(props) {
        super(props);
        this.state = {
          bgColor: ""
        }
      }
    
    
      boxClick = (e) => {
        this.setState({
          bgColor: "red"
        })
      }
    
      render() {
        return (
          <div className="App">
    
    
            <article className='experimentsHolder'>
              <h2>Test 3</h2>
              <p>This is an example of an onClick event 'renderd' by react.</p>
              <div className="boxClickCss" 
              style={{backgroundColor: this.state.bgColor}}
               onClick={this.boxClick}>Click Me!</div>
            </article>
    
          </div>
        );
      }
    }
    

    下面是一个工作示例

    https://codesandbox.io/embed/0p1zmpk4yl

        2
  •  3
  •   Adeel Imran    7 年前

    你可以这样做

    class SampleApp extends React.Component {
      state = {
        color: 'red'
      }
      onChange = () => {
         this.setState({ color: 'green' });
      }
      render () {
        return (
          <div 
           style={{ backgroundColor: this.state.color }} 
           onClick={this.onChange}
          >
            <p>Some content goes here</p>
            <p>Some other content</p>
          </div>
        );
      }
    }
    

    有一个状态 color 默认情况下,这是您想要的颜色,onClick事件触发一个方法,该方法更新 颜色 状态并基于它重新呈现UI。

        3
  •  3
  •   Lafi    7 年前

    我已经对代码进行了分解,这样您甚至可以看到在您的情况下,您可以使用react做些什么 styled-components 库很有帮助,因为它很受欢迎,并且经常与react应用程序一起使用,所以您可以将应用程序组合成可重用和反应性的组件块,这使得react非常强大。 因此,在本例中,我将color属性直接传递给AppWrapper,每个组件都可以有自己的包装器。

    import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    import AppWrapper from './AppWrapper';
    
    const Header = () => (
      <header className='headerStyle'>
        <h1>This is my React test page.</h1>
      </header>
    );
    
    const Article = ({ title, content, divClassName, handleBoxClick, color }) => (
      <div className='experimentsHolder'>
        <h2>{title}</h2>
        <p>{content}</p>
        {handleBoxClick ? (
          <div
            className={divClassName}
            onClick={() => handleBoxClick(divClassName, color)}
          >Click Me!
        </div>
        ) : <div className={divClassName}></div>}
      </div>
    );
    
    class App extends Component {
      state = {
        boxClickCss: 'white',
      }
    
      boxClick = (divClassName, color) => this.setState({ [divClassName]: color });
    
      render() {
        return (
          <AppWrapper state={this.state}>
    
            <Header />
            <Article
              title="Test 1"
              content="This is an example of a static view."
              divClassName="box"
            />
            <Article
              title="Test 2"
              content="This is an example of a basic css animation 'renderd' by react."
              divClassName="boxBounce"
            />
            <Article
              title="Test 1"
              content="This is an example of an onClick event 'renderd' by react."
              divClassName="boxClickCss"
              handleBoxClick={this.boxClick}
              color="red"
            />
    
          </AppWrapper>
        );
      }
    }
    
    export default App;
    

    AppWrapper:

    import styled from 'styled-components';
    
    const AppWrapper = styled.div`
      body {
        background-color:#222;
      }
    
      .headerStyle {
        background-color: #222;
        height: 50px;
        padding: 20px;
        color: white;
        text-align: center;
      }
    
      .experimentsHolder{
        background-color: teal;
        height: 200px;
        border-style: solid;
      }
    
      .box{
        background-color: white;
        height: 10px;
        width: 10px;
      }
    
      .boxBounce{
        background-color: white;
        position: relative; /*without position defined animations wont work*/
        height: 10px;
        width: 10px;
        animation: bounce 5s infinite;
      }
    
      .boxClickCss{
        background-color: ${({ state }) => state.boxClickCss};
        width: 70px;
      }
    
      @keyframes bounce {
        0% {left: 0%;}
        50% {left: 90%;}
        100% {left: 0%;}
      }
    `;
    
    export default AppWrapper;
    
        4
  •  0
  •   Ufuk Yetiskin    2 年前

    您可以使用此管理通过即时反应来更改背景颜色。

     import React from 'react'
        
     class BackgroundColor extends React.Component {
        state = { 
              color : 'red'
        }
        
        changeColor=()=>{
           let color = this.state.color === 'red' ? 'green' : 'red'
           this.setState({color})
        }
        
        
        render(){
          return (
            <div>
              <div style= {{backgroundColor : this.state.color}}>
              </div>
              <button onClick= {this.changeColor}</button>
            </div>
        )
        }
    
    }