首页 > 解决方案 > React - 单击按钮时禁用行

问题描述

我到处寻找这个,但每个例子似乎都不符合我想要的。单击按钮后,对于特定的表格行,我需要禁用该当前行,或者更好地禁用该行上的按钮。

我之前编写的代码只是禁用了每一行的按钮。这是不正确的。对于某些上下文,请参阅我正在编写的应用程序的屏幕截图:

在此处输入图像描述

当用户单击Generate Journey特定行时,我需要禁用该特定行的“生成旅程”按钮,以阻止他们再次执行此操作(这将导致服务器端出现问题)。

我猜对有 React 经验的人来说,这是一项简单的任务,但我尝试了不同的东西,但每一种都没有给我想要的结果。

所以这是我的代码:

上面截图的渲染函数如下:

 render() {
    return (
        <div className="polls-container">
            <div className="dashboard-title" style={{paddingTop: "2%", marginLeft: "-50px"}}>
                <h2>Dashboard</h2>
            </div>
            {
                !this.state.loading && this.state.results.length > 0 ? (
                    <RouteTable buttonDisabled ={this.state.emulateButtonDisabled} results={this.state.results} generateJourney={this.generateJourney} startEmulation={this.getJourneyEmulations}/>
                ) : null
            }
            {
                !this.state.isLoading && this.state.results.length === 0 ? (
                    <div className="no-polls-found">
                        <span>No Active Journey Generations</span>
                    </div>    
                ): null
            }
            {
                this.state.isLoading ? 
                <LoadingIndicator />: null                     
            }
        </div>
    );
}
}  

这基本上调用了Route Table组件,该组件呈现屏幕截图中看到的表格。注意我是如何results={this.state.results} generateJourney={this.generateJourney} startEmulation={this.getJourneyEmulations}作为道具传递下去的。

results 道具基本上就是获取的表数据。'generateJourney' 函数的代码如下(Generate Journey点击按钮时执行):

 generateJourney = (customerId, startDate, endDate, linkedCustomers, lat, lng) => {
   let confirmGenerateJourney = window.confirm('Are you sure you want to start this Journey Generation?')
    if (confirmGenerateJourney) {
        fetch('http://10.10.52.149:8081/generate-journeys', {
            method: 'POST',
            mode:'cors',
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            body: JSON.stringify( {
                customerId: customerId,
                startDate: startDate,
                endDate: endDate,
                serviceIds: linkedCustomers,
                homeLat: lat,
                homeLng: lng
            })
        }).then(response => response.json())
                .catch(err => console.log(err))

        notification.success({
            message: 'Kinesis Fake Telemetry',
            description: "Journey has Started being Generated",
        });

        fetch('http://localhost:8080/api/routeGen/updateCustomerStatus', {
            method: 'PUT',
            mode:'cors',
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            body: JSON.stringify( {
                customerId: customerId,
                status: 1
            })
        }).then(response => response.json())
            .catch(err => console.log(err))

        window.location.reload();
    }
}

没什么特别的,只是简单地调用 API 来 POST 或 PUT 数据。在此之后,startEmulation={this.getJourneyEmulations}这是单击Emulate按钮时单击的代码。这基本上会在我们模拟它之前检查旅程是否已经生成。(等待完成状态)

我的 RouteTable 类如下:

 export class RouteTable extends Component {

constructor(props) {
    super(props);
}

getStatus(result) {
    let status;
    if (result.customerStatus === 0) {
        status = (<Badge color={'secondary'}> Pre Journey Generation</Badge>)
    } else if(result.customerStatus === 1) {
        status = (<Badge color={'success'}> In Journey Generation</Badge>)
    } else if (result.customerStatus === 2) {
        status = (<Badge color={'info'}> Ready for Emulation</Badge>)
    } else {
        status = (<Badge href="/journeyEmulation" color={'danger'}> In Emulation</Badge>)
    }
    return status;
}

render() {
    const {startEmulation, buttonDisabled} = this.props;
    const items = this.props.results.map(result => {
        const serviceIdList = [];
        const deviceRequests = [];

        result.linkedCustomers.map(x => { const emulationData = {"imei": x.imei, "serviceId": x.serviceId, "deviceType": "CALAMP"}
            deviceRequests.push(emulationData)
        });

         result.linkedCustomers.map(x => {serviceIdList.push(x.serviceId);});

        return (
            <tr key={result.linkedCustomerId}>
                <th scope="row">{result.customerName}</th>
                <td>{result.linkedCustomerId}</td>
                <td>{result.numDevices}</td>
                <td>{result.startDate}</td>
                <td>{result.endDate}</td>
                <td>{result.lat}</td>
                <td>{result.lng}</td>
                <td> {this.getStatus(result)}</td>

                <td>
                    <div style={{width:"100%"}}>
                        <Button style={{width: "50%"}} color="primary" onClick={() => this.props.generateJourney(result.linkedCustomerId, result.startDate, result.endDate, serviceIdList, result.lat, result.lng)} disabled={buttonDisabled}>Generate Journey</Button>
                        {' '}
                        <Button style={{width: "50%", marginTop: "4%"}} color="danger" onClick={() => startEmulation(result.linkedCustomerId, result.customerName, result.startDate, result.endDate, deviceRequests)}>Emulate Journey</Button>
                    </div>
                </td>
            </tr>
        )
    })

    return (
        <div className="tableDesign" style={{marginTop: "2%"}}>
        <Table hover>
            <thead>
            <tr>
                <th>Customer Name</th>
                <th>Kinesis Customer Id</th>
                <th>Number of Devices</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Home Lat</th>
                <th>Home Long</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            {items}
            </tbody>
        </Table>
        </div>
    )
}

现在我的问题是如何禁止用户两次生成旅程?我已经尝试过发布的解决方案,它只是禁用每一行的所有按钮。任何帮助将不胜感激,因为这变得令人沮丧!我猜我可以以某种方式使用表格的行键 <tr key {result.linkedCustomerId}>来定位特定按钮以禁用?

谢谢你的帮助 :)

***** 编辑 *****

 generateJourney = (customerId, startDate, endDate, linkedCustomers, lat, lng) => {
   let confirmGenerateJourney = window.confirm('Are you sure you want to start this Journey Generation?')
    if (confirmGenerateJourney) {

        this.setState({generatingId: customerId});

        fetch('http://10.10.52.149:8080/generate-journeys', {
            method: 'POST',
            mode:'cors',
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            body: JSON.stringify( {
                customerId: customerId,
                startDate: startDate,
                endDate: endDate,
                serviceIds: linkedCustomers,
                homeLat: lat,
                homeLng: lng
            })
        }).then(response => {
            this.setState({generatingId: null});
            // response.json();
        }).catch(err => {
            this.setState({generatingId: null});
            console.log(err)
        })

        notification.success({
            message: 'Kinesis Fake Telemetry',
            description: "Journey has Started being Generated",
        });

        fetch('http://localhost:8080/api/routeGen/updateCustomerStatus', {
            method: 'PUT',
            mode:'cors',
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            body: JSON.stringify( {
                customerId: customerId,
                status: 1
            })
        }).then(response => response.json())
            .catch(err => console.log(err))

        // window.location.reload();
    }
}

传递给 RouteTable 的道具

 {
                !this.state.loading && this.state.results.length > 0 ? (
                    <RouteTable generatingId ={this.state.generatingId} results={this.state.results} generateJourney={this.generateJourney} startEmulation={this.getJourneyEmulations}/>
                ) : null
            }

然后在路由表中:

                            <Button style={{width: "50%"}} color="primary" onClick={() => this.props.generateJourney(result.linkedCustomerId, result.startDate, result.endDate, serviceIdList, result.lat, result.lng)} disabled={this.props.generatingId === result.linkedCustomerId}>Generate Journey</Button>

标签: javascriptreactjsdisable

解决方案


一种方法是:

  1. 在您使用的组件上RouteTable,创建一个名为generatingId.
  2. <RouteTable>为被调用者创建一个新道具,generatingId并将this.state.generatingId其作为其值。
  3. 在您的generateJourney函数上,this.setState({generatingId: customerId})在 AJAX 调用之前执行一个。然后在 .then 和 .catch 里面,做一个this.setState({generatingId: null})
  4. 现在在您的RouteTable组件中,更新您的 Row 的生成旅程按钮,如下所示:
<Button style={{width: "50%"}} color="primary" onClick={() => this.props.generateJourney(result.linkedCustomerId, result.startDate, result.endDate, serviceIdList, result.lat, result.lng)} disabled={this.props.generatingId === result.linkedCustomerId}>Generate Journey</Button>

当您单击 Generate Journey 按钮时会发生什么,generateJourney 函数会将客户的 ID 设置为正在生成的 ID。这个新值将被传递给您的 RouteTable,然后将呈现您的表格,并且由于行的按钮将检查generatingId道具是否等于customerId该行所针对的,如果语句为真,它将禁用该行上的按钮.


推荐阅读