简体   繁体   English

访问.jsx元素内的状态

[英]Accessing state inside .jsx element

If I have an element like this: 如果我有这样一个元素:

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

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

How do I use state to change the url , for example? 例如,如何使用state来更改url

I've tried var url = this.state.url but this gives me an error. 我试过var url = this.state.url但这给我一个错误。 This specific portion of code uses arrow functions and I'm not too familiar with them. 代码的这一特定部分使用箭头功能,但我不太熟悉它们。

You should use React Hooks on Functional Component - Using the State Hook – React 您应该在功能组件上使用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>
  );
}

You need to define a React.Component with a render method. 您需要使用render方法定义一个React.Component。 You can't have state if you're not in a 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 }}
    />
    );
  }
};

If you want to use state from a functional component, you need to use the useState hook 如果要使用功能组件中的状态,则需要使用useState挂钩

It is fairly simple to use, just define the initial value, the callback to change it and the name of the state variable and you're set. 使用起来非常简单,只需定义初始值,更改它的回调以及状态变量的名称即可进行设置。 Then you can use the callback to alter the state variable whenever you need to. 然后,您可以根据需要使用回调来更改状态变量。

a simple example: 一个简单的例子:

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