在课堂外访问状态

问题描述 投票:0回答:3

我每次设备旋转时都会更新宽度和高度值。我需要这个值来进行一些计算。这是我的代码

function wp (percentage) {
    const value = (percentage * this.state.viewportWidth) / 100;
    return Math.round(value);
}
const height = this.state.viewportHeight * 0.45; // I am getting the error here

export default class MyClass extends Component {

      onLayout(e) {
        this.updateLayout()
      }

      componentDidMount() {
        this.updateLayout()
      }

      updateLayout = () => {
        const {width, height} = Dimensions.get('window')
        this.setState({viewportWidth: width });
        this.setState({viewportHeight: height });
      }
}

我收到一个错误,告诉我this.state.viewportHeightundefined。你对如何解决这个问题有什么想法吗?

reactjs react-native
3个回答
1
投票

如果要在组件外部使用viewportWidth,则将其作为参数传递给函数。

function wp (percentage, width) {
    const value = (percentage * width) / 100;
    return Math.round(value);
}

目前还不清楚从代码中调用wp函数的位置,但如果从组件内部调用它,则需要用wp(yourPercentageValue, this.state.viewportWidth)替换它

您的高度计算只是漂浮在那里,因此您可以执行相同操作并将其替换为采用视口的函数

功能hp(高度){返回高度* 0.45}

然后你可以在组件中调用hp(this.state.viewportHeight)

状态,在响应中,是组件的状态,因此您永远不能在组件外使用它。你可以将它传递给事物,作为支柱或参数,这就是我上面所做的。


1
投票

如果您的组件与尺寸保持同步,那么您可以直接通过以下方式引用这些尺寸:

Dimensions.get('window').widthDimensions.get('window').height


0
投票

是的,您可以访问外面的州。您需要使用new关键字创建类的实例

    new MyClass().state.viewportWidth
© www.soinside.com 2019 - 2024. All rights reserved.