我是 REACT JS 的新手,所以在制作應用程式時,我被困在這部分,我想在單擊按鈕時更改 h1 值
import Button from 'react-bootstrap/Button';
import './App.css';
import { Container } from 'react-bootstrap';
import { Row } from 'react-bootstrap';
function App() {
return (
<Container>
<Row className="Row">
<div className="frame">
<h1>this text should change</h1>
<Button className=" btn btn1" color="light">YES</Button> // this button should change the text
<Button className=" btn btn2" color="light">NO</Button>
</div>
</Row>
</Container>
);
}
export default App;
uj5u.com熱心網友回復:
永遠不要訪問真正的 DOM。使用狀態并以 React 方式渲染它。
我通常會使用狀態來更改某些內容 - 請參閱
完整的 CodeSandBox:https ://codesandbox.io/s/broken-snow-557w4 ? file =/ src/App.js
uj5u.com熱心網友回復:
在這種情況下,您必須使用鉤子state( Documentation )。
所以,首先你必須匯入 useState 鉤子,然后創建它,最后使用它。
所以,你的代碼將是這樣的:
import Button from 'react-bootstrap/Button';
import './App.css';
import { Container } from 'react-bootstrap';
import { Row } from 'react-bootstrap';
import { useState } from 'react';
function App() {
const [text, setText] = useState("this text should change");
return (
<Container>
<Row className="Row">
<div className="frame">
<h1>{text}</h1>
<Button className=" btn btn1" color="light" onClick={e => setText("new text")}>YES</Button> // this button should change the text
<Button className=" btn btn2" color="light">NO</Button>
</div>
</Row>
</Container>
);
}
export default App;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/388670.html
標籤:javascript 反应 按钮 点击
