在 React 中为按钮单击方法获取"numPlay is 未定义"错误



我试图调用nextPage()在getConfirm当有人点击按钮"Confirm",但它说,numPlay从来没有在getConfirm()方法中定义。

请有人帮助我理解为什么/修复它!谢谢你

const root = ReactDOM.createRoot(document.getElementById('root'));
const title = 
<h1 style={{ fontSize: "40px" }}>
Draft
</h1>
const numPlayers = (
<div id="numPlayers">
{title}
<h1 style={{ fontSize: "20px" }}>
How many players would you like to draft with?
</h1>
<input id="numPlay" placeholder="Number of players" type="number"></input>
<div>
</div>
<button id="confirm" onClick={getConfirm}>
Confirm
</button>
</div>
);
function getConfirm() {
var numPlay = document.getElementById("numPlay");
root.render(nextPage);
}
const nextPage = (
<div>
{title}
<h1 style={{ fontSize: "20px" }}>
How many draftees are there?
{numPlay}
</h1>
</div>
)
root.render(numPlayers);


您需要在getCOnfirm之外声明numPlay:

import React from 'react';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
const title = <h1 style={{ fontSize: '40px' }}>Draft</h1>;
let numPlay;
const numPlayers = (
<div id="numPlayers">
{title}
<h1 style={{ fontSize: '20px' }}>
How many players would you like to draft with?
</h1>
<input id="numPlay" placeholder="Number of players" type="number"></input>
<div></div>
<button id="confirm" onClick={getConfirm}>
Confirm
</button>
</div>
);
function getConfirm() {
numPlay = document.getElementById('numPlay');
root.render(nextPage);
}
const nextPage = (
<div>
{title}
<h1 style={{ fontSize: '20px' }}>
How many draftees are there?
{numPlay}
</h1>
</div>
);
root.render(numPlayers);

但是为什么你使用React通过调用.render命令式,你试图集成一些React组件上已经存在的SPA?

相关内容

最新更新