簡體   English   中英

可以從外部類調用類函數

[英]It is possible to call class function from outside class

我試圖從類外部調用函數並更新類的狀態。 這是正確的方法嗎?

    function  myFunc() {
       this.Test("test")
    }

    class Notification extends Component {

      constructor(props) {
        super(props);
        this.state = {
            demoState:''
        };
      }

      Test(data){

       this.setState({
           demoState:data 
         })
      }

      render(){
         return(<div/>)
      }
}

您未在示例中提供函數用法。

正確的方法是大多數功能的工作方式。 但是不要通過使用this參數來取笑react.js-只需將參數傳遞給myFunc

是, this參數傳遞給myFunc。

function  myFunc(this /* <----- */) {
   this.Test("test")
}

然后從類內部調用myFunc,如下所示:

myFunc(this);

可能是,您需要傳遞該類的對象才能更改狀態。 看看myFunc和Notification.Test函數的變化。

function myFunc() {
  let notification = new Notification({});
  notification.Test("test");
  console.log(notification.state);
}

class Notification extends Component {

  constructor(props) {
    super(props);
    this.state = {
      demoState: ''
    };
  }

  Test(data) {

    this.state = {
      demoState: data
    };
  }

  render() {
    return ('<div/>')
  }
}

暫無
暫無

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

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