在React函数中做很多事情

Cod*_*uce 3 javascript reactjs

我想知道单击按钮时是否有可能在组件中进行多种操作。

目前,我有一个简单的组件。单击该按钮时,它会向数组添加一个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;
Run Code Online (Sandbox Code Playgroud)

Chr*_*Ngo 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;
Run Code Online (Sandbox Code Playgroud)