javascript 如何通过onClick事件从状态访问内部变量

iyfjxgzm  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(107)

我有一个React应用程序当我按下按钮不显示结果:测试
对于null,它是可以的,但是我不能显示getNewResult函数的结果!!

import React from 'react';

function ResultDisplayer({ getNewResult }){
    let result = null;
    
    function handleClick(){
        result = getNewResult();
    }
    
    return (<div>
        <button id="button" onClick={handleClick}>Click</button>
        {result != null && <span id="result">{result}</span>}
    </div>);
}

export function Preview() {
    return <ResultDisplayer getNewResult={() => 'test'} />;
}

export default ResultDisplayer;
5fjcxozz

5fjcxozz1#

您需要使用stateuseState()),以便在状态更改时重新呈现组件:

function ResultDisplayer({ getNewResult }){
    let [result, setResult] = React.useState(null);
    
    function handleClick(){
        setResult(getNewResult());
    }
    
    return (
      <div>
        <button id="button" onClick={ handleClick }>Click</button>
        
        { result != null && <div id="result">{ result }</div> }
      </div>
    );
}

const App = () => {
  return <ResultDisplayer getNewResult={() => 'test'} />;
}

ReactDOM.render(<App />, document.querySelector('#app'));
body {
  font-family: monospace;
  margin: 0;
}

#app {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

button {
  font-family: monospace;
  font-weight: bold;
  border-radius: 4px;
  padding: 8px 16px;
  box-shadow: inset 0 0 0 2px black;
  background: transparent;
  overflow: hidden;
  transition: all ease-in 300ms;
  outline: none;
  border: 0;
  cursor: pointer;
  display: block;
}

#result {
  margin-top: 16px;
  padding: 8px 16px;
  text-align: center;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

相关问题