我使用了一个使用React的webapp。我的代码当前创建了一个按钮列表,可以根据用户单击的随机生成的按钮更改圆的颜色。为了增强我的代码,当用户单击按钮时,我希望所有按钮的颜色都改变,因此需要更新按钮的所有onClick函数,因为它们将它们的颜色作为参数传递给更改圆的颜色的函数。下面是我目前的解决方案:它要求我移除每个按钮,然后完全重建按钮。仅仅使用button.onclick = function() { newOnclickFunction}是行不通的,我自己也找不到答案。任何帮助都将不胜感激;我几乎可以肯定还有比这更好的方法。
let reflipPalleteCompletely = () => {
let everyButtonPossible = document.getElementsByClassName("colorChangeButton")
for( var button of everyButtonPossible){
button.style.backgroundColor = randomColor()
let myParent = button.parentElement
myParent.removeChild(button)
let freshButton = document.createElement("button", {value: "Click", className: "colorChangeButton", })
freshButton.innerHTML = 'Click'
freshButton.className = 'colorChangeButton'
freshButton.style.backgroundColor = randomColor()
let newOnclickFunction = () => { changeToNewColor(button.style.backgroundColor); reflipPalleteCompletely() }
freshButton.onclick = function() { newOnclickFunction() }
myParent.appendChild(freshButton)
发布于 2018-06-21 05:03:25
简短的答案是:如果每个按钮都应该改变颜色以反映它所代表的颜色值,并且每次按下按钮时都会重新随机化这组颜色,那么您不能也不应该避免重新呈现按钮。
然而,Mike是对的:如果您正在编写自己的元素创建脚本,那么您就没有正确地使用React。
您的组件可能如下所示:
const buttonCount = 10
class Demo extends React.Component {
constructor(props) {
super(props)
this.state = {
currentColor: getRandomColor()
}
}
setColor = (newColor, event) => {
this.setState({
currentColor: newColor
})
}
render() {
let {
currentColor
} = this.props
let colorChoices = Array(buttonCount)
.fill()
.map(() => getRandomColor())
return (
<div className="Demo">
<div className="the-shape" style={{ backgroundColor: currentColor }} />
<ol className="color-choices">
{
colorChoices.map( color => (
<button key={ color }
style={{ backgroundColor: color }}
onClick={ this.setColor.bind(this, color) }
>
{ color }
</button>
))
}
</ol>
</div>
)
}
}
这一切都取决于你是否有一个可以生成颜色的getRandomColor
函数。而且它没有解决确保选择不包括当前颜色的问题(尽管您可以很容易地做到这一点,例如,生成2n
颜色,过滤掉currentColor,然后获取第一个n
,等等)。
如果你真的讨厌重画按钮,你可以保存它们的引用,然后让setColor
方法遍历它们并修改它们的样式。
但React的要点是避免DOM的过程性突变,而是支持声明所需的DOM,并让React引擎找出有效的突变策略。
对您提出的问题的直接回答:“更改HTML元素的.onClick元素的最佳方法是什么?”可能是:找到一种不需要每次都更改函数的模式。
而不是这样:
let newOnclickFunction = () => { changeToNewColor(button.style.backgroundColor); reflipPalleteCompletely() }
试试下面这样的代码:
function onClickButton(event) {
let button = event.target
let color = button.style.backgroundColor
changeToNewColor(color)
}
这样,所需的颜色值就不会被添加到onClick函数中。相反,该函数会检查按钮,并将其背景用作changeToNewColor
的参数。
使用一些巧妙的CSS,您可以将所需的颜色写入每个按钮上的data-
道具,并让浏览器根据该颜色计算background-color
。然后,您可以在包含所有按钮的某个祖先元素上使用事件委托,它侦听具有该data-
属性的任何元素上的单击,并执行与上面相同的工作。这样,您甚至不需要在每个按钮上都有一个单击功能。
https://stackoverflow.com/questions/50956782
复制相似问题