简体   繁体   中英

React JS- not able to detect 'show' function

I am trying to build a simple click counter in which the counter will increase by 1(initially 0) with each click. But the error I am getting is 'show' is defined but never used .The function 'show' re-renders the DOM after each click as given in index.js file.

App.js file-

import './App.css';
import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div onClick={this.props.onClick}>This div has been clicked {this.props.clicks} times.</div>
    );
  }

}

export default App;

index.js file-

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

let model = { clicks: 0 };

function show() {
  ReactDOM.render(<App clicks={model.clicks} onClick={()=> { model.clicks += 1; show();}} />, document.getElementById('root'));
}

reportWebVitals();

Change your index.js

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

class Index extends React.Component {
  state = {
    clicks: 0
  };

  render() {
    return (
      <App
        clicks={this.state.clicks}
        onClick={() => this.setState((props) => ({ clicks: props.clicks + 1 }))}
      />
    );
  }
}

ReactDOM.render(<Index />, document.getElementById("root"));

Codesandbox: https://codesandbox.io/s/dark-firefly-i30t5?file=/src/index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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