首页 > 解决方案 > 访问 .jsx 元素内的状态

问题描述

如果我有这样的元素:

const CardWebView = () => {
  const url = 'xxx';

  return (
    <WebView
    source={{
      uri: url,
    }}
    onNavigationStateChange={this.onNavigationStateChange}
    startInLoadingState
    javaScriptEnabled
    style={{ flex: 1 }}
  />
  );
};

例如,我如何使用state来更改url

我试过var url = this.state.url了,但这给了我一个错误。这部分代码使用箭头函数,我对它们不太熟悉。

标签: javascriptreact-native

解决方案


你应该在功能组件上使用 React Hooks -使用 State Hook - React

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

推荐阅读