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

Trying to create a toggle function to set the state of 2 buttons from disabled to enabled based on an onClick event attached to a third button

我有一组 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'));

你快到了。

在您的渲染方法中,您设置了 disabled={true},这意味着它将永久保持 true,而不是检查 disabled 的值 属性 处于状态。

toggle 方法应该简单地否定 disabled.

的先前值
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'));

此外,考虑使用某种切换组件代替第三个按钮以获得更好的用户体验。