javascript - 在 React 中为一组按钮,单击后如何更改颜色同时还记录哪些按钮/按钮被单击?
问题描述
我有一个子组件,它是一个按钮,在单击状态更新后会改变颜色。但是,我还需要在一组此类按钮中识别出哪个按钮被单击。沙箱或以下代码。我该怎么做?如果我对子组件有操作,那么如何正确调用父组件上的 onclick?
按钮.js
import React, { Component } from 'react';
import './style.css'
class Button extends React.Component {
constructor(props){
super(props);
this.state = {
clicked: false
}
}
changeColor=()=>{
this.setState({clicked: !this.state.clicked})
}
render(){
let btn_class = this.state.clicked ? "redButton" : "whiteButton";
return (
<button className={btn_class} onClick={this.changeColor.bind(this)}>
{this.props.name}
</button>
)
}
}
export default Button;
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Button from './button.js'
const btns= ['button1','button2','button3']
const n = btns.length
class App extends Component {
constructor() {
super();
this.state = {
clickedBtn : "",
btnStyle: new Array(n)
};
}
handleClick= (index) =>
{
alert(index)
}
render() {
return (
<div>
{btns.map((btn, index) => (
<Button
name={btn}
onClick={this.handleClick.bind(this,index)}/>
))}
</div>
);
}
}
render(<App />, document.getElementById('root'));
解决方案
您可以尝试类似的方法,最后您将在 clickedButton 对象中单击按钮值。
import React, { Component } from 'react';
import './style.css'
class Button extends React.Component {
constructor(props){
super(props);
this.state = {
clicked: false
}
}
changeColor=()=>{
this.setState({clicked: !this.state.clicked})
this.props.onButtonClick(this.props.index)
}
render(){
let btn_class = this.state.clicked ? "redButton" : "whiteButton";
return (
<button className={btn_class} onClick={this.changeColor.bind(this)}>
{this.props.name}
</button>
)
}
}
export default Button;
index.js
class App extends Component {
constructor() {
super();
this.state = {
clickedBtn : {},
btnStyle: new Array(n)
};
}
handleClick= (index) =>
{
let clickedBtn = this.state.clickedBtn
if(clickedBtn[index]){
delete clickedBtn[index]
} else{
clickedBtn[index]= true
}
}
render() {
return (
<div>
{btns.map((btn, index) => (
<Button
name={btn}
index={index}
onButtonClick={this.handleClick}/>
))}
</div>
);
}
}
render(<App />, document.getElementById('root'));
推荐阅读
- wkhtmltopdf - wkhtmltopdf的替代品
- ios - UIStoryboard的自定义UIComponent的制作方式
- c# - 类方法不使用类变量
- reactjs - 在 MUI 主题中动态更改原色
- javascript - node.js 查询未完全执行并返回主块
- react-native - 未定义不是反应原生的对象(评估_this.ref.method)
- css - gatsby-image:如何将处理后的图像导入 css 并与 background-image 属性一起使用
- javascript - WordPress - 将所有媒体库文件移动到新文件夹(棘手)
- jmeter - 以分布式模式打开 JMeter
- javascript - 通过 jQuery 应用时出现“宽度”问题