我想知道单击按钮时是否可以操纵组件中的多个事物。
目前,我有一个简单的组件。单击按钮时,它会向数组添加一个ID ...非常简单的内容。
但是当按下按钮时,我还想将按钮文本更改为“已选择”,然后在按钮上添加“ color =“ danger””标签。
我发现这真的很难。任何帮助将不胜感激。
import React, { Component } from "react";
import { Col, Card, CardBody, Button } from "reactstrap";
class ThisComponent extends Component {
addResponse(id) {
this.props.addResponseInState(id);
}
render() {
const { id } = this.props;
return (
<Col>
<Card>
<CardBody>
<Button onClick={() => this.addResponse(id)}>Select</Button>
</CardBody>
</Card>
</Col>
)
}
}
export default ThisComponent;
答案 0 :(得分:7)
您应该熟悉使用组件状态,这是React的基础。
State
本质上可以帮助您始终跟踪组件,无论是某种状态还是要维护的数据。
import React, { Component } from "react";
import { Col, Card, CardBody, Button } from "reactstrap";
class ThisComponent extends Component {
state = {
clicked: false
}
addResponse(id) {
this.props.addResponseInState(id);
this.setState({
clicked: true
})
}
render() {
const { id } = this.props;
return (
<Col>
<Card>
<CardBody>
<Button
color={this.state.clicked ? "danger" : ""}
onClick={() => this.addResponse(id)}
>
{ !this.state.clicked ? "Select" : "Selected"}
</Button>
</CardBody>
</Card>
</Col>
)
}
}
export default ThisComponent;
答案 1 :(得分:0)
您可以在函数中做任何您想做的事情。但是,如果要在其中存储一些数据,还应该向组件添加状态。
import React, { Component } from "react";
import { Col, Card, CardBody, Button } from "reactstrap";
class ThisComponent extends Component {
constructor(props) {
super(props);
this.state = {
isSelected: false,
}
}
addResponse(id) {
this.props.addResponseInState(id);
this.setState({isSelected: true})
}
render() {
const { id } = this.props;
const { isSelected } = this.state;
return (
<Col>
<Card>
<CardBody>
<Button
onClick={() => this.addResponse(id)}
className={isSelected ? 'selected' : ''}
>
Select
</Button>
</CardBody>
</Card>
</Col>
)
}
}
export default ThisComponent;