0

如标题所示,如下所示

class T extends React.Component {
    constructor(props) {
        super(props)
        this.a = false;
    }

    methodA {
    //will set 'a' in this method, maybe async.
    }

    methodB {
    // will get 'a' in this method.
    }

    render() {
        return (
                   <div>hello,world</div>
        )
    }
}

这看起来像一个非常简单的代码。但是随着组件的复杂化和逻辑的提升,我们需要在类中添加更多的属性来满足方法的通信,比如:

> class T extends React.Component {
>      constructor(props)
>        this.a = false;
>        this.b = 123;
>        this.c = 'string';
>        this.d = null;
>        this.e = [];
>        ...
>        this.z = ........
>      }

显然,这并不像样。那么,您能否告诉我我们是否有任何其他解决方案来替代它?我们有什么体面的方式在一个类中的方法之间进行通信吗?提前致谢。

4

1 回答 1

1

如果我理解您的要求,您只是希望能够在组件中的不同方法之间引用相同的变量?尝试this.state在您的构造函数中使用。

Class T extends React.Component {
  this.state = {
    a: false,
    b: 123,
    c: 'string',
    ...
  }
}

然后您可以在组件中的任何其他位置引用这些变量...

this.setState()您可以通过内置于 React.Component的函数更改这些变量。

  methodA() {
    return this.state.b * 2
  }

  methodB() {
    this.setState({ c: 'new string' })
  }
于 2021-03-30T14:10:58.527 回答