import { useState } from "react";
import "./styles.css";
function App() {
const [InputVal, setInputVal] = useState();
const [ShowDiv, setShowDiv] = useState(
<div>
<p>Hello world. This is default "Show Div" value</p>
</div>
);
const ChangeDivFunc = () => {
setShowDiv(
<div>
<p style={{ color: "red" }}>
Hello World. This is updated "Show Div" value
</p>
<input onChange={getInputval} type="text" />
<br />
<br />
<button onClick={AlertVal}>Show Input Value</button>
</div>
);
};
const getInputval = (val) => {
setInputVal(val.target.value);
};
const AlertVal = () => {
alert(InputVal);
};
return (
<div className="App">
<h1>Example</h1>
<br />
<button onClick={ChangeDivFunc}>Change Div</button>
{ShowDiv}
</div>
);
}
export default App;
代碼流程:
- 單擊更改 Div按鈕,然后它將顯示輸入欄位和顯示輸入值按鈕。
- 現在,在輸入欄位中輸入一些值,然后單擊“顯示輸入值”按鈕以獲取輸入欄位的值。
問題:它回傳undefined而不是輸入欄位值。
單擊“顯示輸入值”按鈕時,我試圖獲取“輸入”欄位的值。但我沒有得到想要的結果。
這是沙盒鏈接:點擊代碼
uj5u.com熱心網友回復:
不要將 html 節點存盤在 state 中。您可以簡單地僅存盤一個布林值以在要顯示的節點之間切換。我不太確定,但它可能會導致奇怪的行為,因為 React 內部在很大程度上依賴于 DOM/HTML UI 樹(請參閱管理狀態)。
試試這個:
import { useState } from "react";
import "./styles.css";
function App() {
const [inputVal, setInputVal] = useState(""); // initialize as empty string.
const [showDiv, setShowDiv] = useState(false);
const changeDivFunc = () => {
setShowDiv(true);
};
const getInputVal = (event) => { // The arg is Event object, not val
setInputVal(event.target.value);
};
const alertVal = () => {
alert(inputVal);
};
return (
<div className="App">
<h1>Example</h1>
<br />
<button onClick={changeDivFunc}>Change Div</button>
{
showDiv? (
<div>
<p style={{ color: "red" }}>
Hello World. This is updated "Show Div" value
</p>
<input value={inputVal} onChange={getInputVal} type="text" />
<br />
<br />
<button onClick={alertVal}>Show Input Value</button>
</div>
) : (
<div>
<p>Hello world. This is default "Show Div" value</p>
</div>
)
}
</div>
);
}
export default App;
分叉代碼筆
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/378038.html
標籤:javascript 反应
