javascript 如何使用反应“onClick”来更改元素的 style.backgroundColor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48251597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use reacts 'onClick' to change a style.backgroundColor of an element
提问by Ghoyos
Ive been experimenting with react recently and would like to know how to use reacts 'onClick' syntax to change the background color of an element. The relevant pages in regards to this question are on my git hub account and both are App.jsand App.css.
我最近一直在试验 react,想知道如何使用 reacts 的“onClick”语法来更改元素的背景颜色。关于这个问题的相关页面在我的 git hub 帐户上,都是App.js和App.css。
As you can see; Ive gotten to the point where once you 'click' the element that has the text within it 'click me!' - it calls the function boxClick(). But once that code within box click is ran it give an error -> (imgurPic). Now if this was a vanilla js page I could easily make this work but im new to react. I would like to know how to make this function work properly and also why the current code isnt working. In my mind I have indeed defined 'boxClickCss' when I used a document.getElementsByClassName; which is why I dont understand this error.
如你看到的; 我已经到了当你“点击”其中包含文本的元素“点击我!”的地步。- 它调用函数 boxClick()。但是一旦运行框点击中的代码,它就会给出错误 -> (imgurPic)。现在,如果这是一个普通的 js 页面,我可以轻松完成这项工作,但我是新手。我想知道如何使这个函数正常工作,以及为什么当前的代码不起作用。在我看来,当我使用 document.getElementsByClassName 时,我确实定义了“boxClickCss”;这就是为什么我不明白这个错误。
回答by Sajith Dilshan
In React it is a bad practise to directly manipulate the actual DOM since React changes are first applied in the virtual DOM and then only the difference is modified in the real DOM. Further, when your function is being called, there might be a chance that the DIV is not actually present in the real DOM.
在 React 中,直接操作实际 DOM 是一种不好的做法,因为 React 更改首先应用于虚拟 DOM,然后仅在真实 DOM 中修改差异。此外,当您的函数被调用时,DIV 可能实际上并不存在于真实的 DOM 中。
You can find out more about the lifecycle of a React component and how you can manipulate the component behaviour and appearance at each lifecycle stage by reading the official documentation.
您可以通过阅读官方文档了解更多关于 React 组件的生命周期以及如何在每个生命周期阶段操纵组件行为和外观的信息。
However, as for your problem, you need to use the stateto change the color of the DIV. Below is the code (Only the modified part is included.)
但是,对于您的问题,您需要使用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>
);
}
}
Here is a working example
这是一个工作示例
回答by Lefi Tarik
I've re-factored the code so you could even see what you could do with react, in your case styled-componentslibrary helps well since it is popular and a lot used with react applications, you could compose your app into chunks of components that are reusable and reactive, that makes react very powerful. So in this example i've passed the color property to the AppWrapper directly, and each component could have it's own wrapper.
我已经重构了代码,所以你甚至可以看到你可以用 react 做什么,在你的例子中styled-components库很有帮助,因为它很流行并且经常与 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;
the 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;
回答by Adeel Imran
You can do something like this
你可以做这样的事情
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>
);
}
}
Have a state colorwhich is by default the color you want, and onClick event trigger a method which updates the colorstate and re-renders your UI based on it.
拥有一个color默认为您想要的颜色的状态,并且 onClick 事件触发一个方法,该方法更新color状态并基于它重新呈现您的 UI。

