是否可以使用多个按钮的onClick功能更改背景颜色?
此代码将同时更改两个按钮的颜色(初始为黑色)。
我想我单击的按钮会更改颜色,但另一个按钮不会更改。
例如:第一次,Btn1黑色,btn2黑色
然后单击btn1,btn1白色btn2黑色,
然后单击btn2,btn1白色,btn2白色。
然后单击btn2,btn1白色,btn2黑色。
class Test extends React.Component {
constructor(){
super();
this.state = {
color_black: true
}
}
changeColor(){
this.setState({color_black: !this.state.color_black})
}
render(){
let bgColor = this.state.color_black ? "black" : "white"
return (
<div>
<button style={{backgroundColor: bgColor}} onClick={this.changeColor.bind(this)}>Button1</button>
<button style={{backgroundColor: bgColor}} onClick={this.changeColor.bind(this)}>Button2</button>
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
最简单的解决方案是将按钮放置在单独的组件中,而不是将它们呈现在父组件中。由于一个组件一次只能具有一个状态,因此必须进行分隔。很多代码?是。它有效吗?也可以
/*
* A simple React component
*/
class Button extends React.Component {
constructor(){
super();
this.state = {
color_black: true,
}
}
changeColor(){
this.setState({color_black: !this.state.color_black})
}
render(){
let bgColor = this.state.color_black ? this.props.color : this.props.color2
return (
<div>
<button style={{backgroundColor: bgColor}} onClick={this.changeColor.bind(this)}>Button1</button>
</div>
)
}
}
class Application extends React.Component {
render(){
return (
<div>
<Button color="blue" color2="red"/>
<Button color="black" color2="white"/>
</div>
)
}
}
/*
* Render the above component into the div#app
*/
React.render(<Application />, document.getElementById('app'));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句