简体   繁体   English

基于 React.Component 的类

[英]Classes based on React.Component

New, new, new to React. React 的新的、新的、新的。 Downloaded the following sample of setState method in classes that extend React.Component.在扩展 React.Component 的类中下载了以下 setState 方法示例。 It works fine, but I'm not understanding why no object needs to be instantiated for App, since each user could be in a different location...它工作正常,但我不明白为什么不需要为 App 实例化 object,因为每个用户可能位于不同的位置......

I somehow thought index.js would need:我以某种方式认为 index.js 需要:

const app = new App()

Is there a reason for this?是否有一个原因?

index.js index.js

import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

App.js应用程序.js

import React from 'react';
import ReactDOM from 'react-dom';
import logo from './logo.svg';
import './App.css';


class App extends React.Component {
    constructor ( props ) {
        super ( props );
        this.state={ latitude: null};

        window.navigator.geolocation.getCurrentPosition (
            ( postion ) => {
                this.setState( {latitude: postion.coords.latitude })
            },
            ( error ) => console.log ( error )
        );
    }

    render () {


        return (
            <div className="App">
                <header className="App-header">
                    <p>
                        LATITUDE: {this.state.latitude}
                    </p>
                </header>
            </div>
        );
    }
}

export default App;

Actually you do instanciate objects everytime you use a React component.实际上,每次使用 React 组件时都会实例化对象。 You can translate const app = new App() by using <App/> in your code.您可以在代码中使用<App/>来翻译const app = new App() In your case, one instance is in the ReactDOM.render function.在您的情况下,一个实例位于 ReactDOM.render function 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM