簡體   English   中英

無法訪問 Ant Modal 中的 this.setState 或 this.state 確認 ok/cancel 功能

[英]Cannot access this.setState or this.state inside Ant Modal confirm ok/cancel function

我在this.setState /onOk 函數中訪問this.statethis.setState遇到問題。 我想在確認或取消彈出模態后修改狀態。 如果有人有不同的方法,您的指導會有所幫助。

import React from 'react';
import { Button, Modal } from 'antd';

class ExampleClass extends React.Component {
  constructor() {
    super();

    this.state = {
      bankInfo: 100,
    };
  }

  onButtonClicked() {
    this.setState({ bankInfo: 200 });            // works fine
    Modal.confirm({
      title: 'Are you sure delete this item?',
      okType: 'danger',
      onOk() {
        this.setState({ bankInfo: 300 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
      },
      onCancel() {
        this.setState({ bankInfo: 400 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
      },
    });
  }

  render() {
    return (
      <div>
        <Button onClick={this.onButtonClicked.bind(this)}>Click Me</Button>
      </div>
    );
  }
}

export default ExampleClass;

我更喜歡使用箭頭函數

import React from 'react';
import { Button, Modal } from 'antd';

class ExampleClass extends React.Component {
  constructor() {
    super();

    this.state = {
      bankInfo: 100,
    };
  }

  onButtonClicked = () => {
    this.setState({ bankInfo: 200 });
    Modal.confirm({
      title: 'Are you sure delete this item?',
      okType: 'danger',
      onOk: () => {
        this.setState({ bankInfo: 300 });
      },
      onCancel: () => {
        this.setState({ bankInfo: 400 });
      },
    });
  }

  render() {
    return (
      <div>
        <Button onClick={this.onButtonClicked}>Click Me</Button>
      </div>
    );
  }
}

export default ExampleClass;

您需要將您的方法綁定到類。

import React from 'react';
import { Button, Modal } from 'antd';

class ExampleClass extends React.Component {
  constructor() {
    super();

    this.state = {
      bankInfo: 100,
    };
  }
  onOkHandler = () => {this.setState({ bankInfo: 300 })}
  onCancelHandler = () => {this.setState({ bankInfo: 400 })}
  onButtonClicked() {
    this.setState({ bankInfo: 200 });            // works fine
    Modal.confirm({
      title: 'Are you sure delete this item?',
      okType: 'danger',
      onOk() {
        this.onOkHandler()
      },
      onCancel() {
       this.onCancelHandler()
      },
    });
  }

  render() {
    return (
      <div>
        <Button onClick={this.onButtonClicked.bind(this)}>Click Me</Button>
      </div>
    );
  }
}

export default ExampleClass;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM