尝试创建一个切换函数,以根据附加到第三个按钮的 onClick 事件将 2 个按钮的状态从禁用设置为启用



>我有一组 3 个按钮,我需要将两个按钮的初始状态设置为禁用,然后为第三个按钮创建一个 onClick 事件,该事件将在单击时启用这两个按钮。我正在考虑在状态中设置禁用属性,然后为 onClick 创建函数,该函数将针对两个按钮的状态并将其设置为false。我当前的代码如下,关于如何实现这一点的任何想法?

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Button } from 'antd';
import "antd/dist/antd.css";
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
disabled: undefined
};
}
toggleSwitch(){
alert("you clicked the switch");
}
render() {
return (
<div>
<Button disabled={true}>Modify Docs</Button>
<Button disabled={true}>Upload Docs</Button>
<Button onClick={this.toggleSwitch}>Unlock Quote</Button>
</div>
);
}
}
render(<App />, document.getElementById('root'));

你快到了。

在 render 方法中,你已设置disabled={true}这意味着它将永久保持true,而不是检查处于 state 的禁用属性的值。

切换方法应简单地否定先前的禁用值。

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Button } from 'antd';
import "antd/dist/antd.css";
import './style.css';
class App extends Component {
state = {
disabled: true,
};
toggleSwitch() {
// when toggling, we just negate the previous value
this.setState(previousState => ({
disabled: !previousState.disabled,
}))
}
render() {
// Buttons will use the same value from state
// to check if they should be disabled
const { disabled } = this.state;
// instead of setting disabled={true}, reference the disabled
// property from state
return (
<div>
<Button disabled={disabled}>Modify Docs</Button>
<Button disabled={disabled}>Upload Docs</Button>
{/* we set the text of the button depending on the value of disabled */}
<Button onClick={this.toggleSwitch}>
{disabled ? 'Unlock Quote' : 'Lock Quote'}
</Button>
</div>
);
}
}
render(<App />, document.getElementById('root'));

此外,请考虑使用各种切换组件而不是第三个按钮,以获得更好的用户体验。

最新更新