[英]Getting undefined instead of Input Field value
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;
代碼流程:
問題:它返回未定義而不是輸入字段值。
單擊顯示輸入值按鈕時,我試圖獲取輸入字段的值。 但我沒有得到預期的結果。
這是沙盒鏈接: 點擊獲取代碼
不要將 html 節點存儲在 state 內。 您可以只存儲一個 boolean 值來在要顯示的節點之間切換。 我不太確定,但它可能會導致奇怪的行為,因為 React 在內部很大程度上依賴於 DOM/HTML UI 樹(請參閱 管理 State )。
試試這個:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.