在 React 中,如何通過單擊/更改另一個元素來獲取另一個元素的值?
<div>
<input {get this value}/>
<button onClick={()=> console.log(get value of above input field)}/>
</div>
uj5u.com熱心網友回復:
您可以使用
const [inputValue, setInputValue] = useState("");
function onInputChange(e) {
setInputValue(e.target.value);
}
const getValue = () => console.log(inputValue);
return (
<div>
<input value={inputValue} onChange={onInputChange} />
<button onClick={getValue}>get value</button>
</div>
);
2)使用useRef鉤子取消控制輸入
const inputRef = useRef("");
const getValue = () => console.log(inputRef.current.value);
return (
<div>
<input ref={inputRef} />
<button onClick={getValue}>get value</button>
</div>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336565.html
標籤:javascript 反应
上一篇:如何使用陣列值更新div的背景
