簡體   English   中英

訪問.jsx元素內的狀態

[英]Accessing state inside .jsx element

如果我有這樣一個元素:

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但這給我一個錯誤。 代碼的這一特定部分使用箭頭功能,但我不太熟悉它們。

您應該在功能組件上使用React掛鈎- 使用狀態掛鈎– 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>
  );
}

您需要使用render方法定義一個React.Component。 如果您不在組件中,就無法獲得狀態

const CardWebView = <CardWebView />

class CardWebView extends React.Component{
  constructor(props) {
     super(props);
     this.state = {url: 'xxx'};
  }

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

如果要使用功能組件中的狀態,則需要使用useState掛鈎

使用起來非常簡單,只需定義初始值,更改它的回調以及狀態變量的名稱即可進行設置。 然后,您可以根據需要使用回調來更改狀態變量。

一個簡單的例子:

import React, { useState } from 'react';
import { Text, View } from 'react-native';

const App = () => {

  const [url, setUrl] = useState('something')

  return (
    <View>
      <Text>{url}</Text>
      <Text onPress={() => setUrl('something new')}>Click me</Text>
    </View>
  );
}

export default App;

暫無
暫無

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

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