简体   繁体   English

React JS-无法检测到“显示”function

[英]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.我正在尝试构建一个简单的点击计数器,每次点击计数器都会增加 1(最初为 0)。 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.但是我得到的错误是“显示”已定义但从未使用过。function“显示”在每次单击后重新呈现 DOM,如 index.js 文件中给出的那样。

App.js file- App.js 文件-

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- index.js 文件-

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改变你的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代码沙盒: https://codesandbox.io/s/dark-firefly-i30t5?file=/src/index.js

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

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