如何使用反应' onClick'更改元素

时间:2018-01-14 16:19:25

标签: javascript css reactjs

我最近一直在试验反应,并想知道如何使用反应' onClick'用于更改元素背景颜色的语法。有关此问题的相关网页位于我的git hub帐户中,均为App.jsApp.css

正如你所看到的;我已经到了一旦你点击了#39;其中包含文字的元素'点击我!' - 它调用函数boxClick()。但是,一旦在框中单击该代码,就会出现错误 - > (imgurPic)。现在,如果这是一个vanilla js页面,我可以轻松地完成这项工作,但我很快就会做出反应。我想知道如何使这个功能正常工作,以及为什么当前的代码不工作。在我看来,我确实定义了“boxClickCss”#39;当我使用document.getElementsByClassName;这就是为什么我不理解这个错误。

3 个答案:

答案 0 :(得分:2)

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

您可以阅读official documentation,了解有关React组件生命周期的更多信息,以及如何在每个生命周期阶段操纵组件行为和外观。

但是,至于您的问题,您需要使用state来更改DIV的颜色。下面是代码(仅包含修改后的部分。)

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

答案 1 :(得分:1)

你可以做这样的事情

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事件会触发更新color状态并根据其重新呈现UI的方法。

答案 2 :(得分:1)

我已经重新考虑了代码,所以你甚至可以看到你可以做什么做出反应,在你的情况下styled-components库很有帮助,因为它很受欢迎并且很多用于反应应用程序,你可以编写你的应用程序成为可重用和反应的组件块,这使得反应非常强大。 所以在这个例子中我直接将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;