我在我的反應組件之一中有這種形式
<div className="form-check">
<input
type="radio"
className="form-check-input"
value={3}
name="priority"
/>
<label className="form-check-label">High Priority</label>
</div>
<div className="form-check">
<input
type="radio"
value={2}
className="form-check-input"
name="priority"
/>
<label className="form-check-label">Medium Priority</label>
</div>
<div className="form-check">
<input
type="radio"
value={1}
className="form-check-input"
name="priority"
/>
<label className="form-check-label">Low Priority</label>
</div>
然后我在按鈕上有一個 onclick 功能。我想在我的函式中獲取無線電表單的值。我怎么做?有沒有辦法用 useRef 鉤子來做到這一點?注意:我使用的是功能組件,因此任何帶有類組件的解決方案都無濟于事。
謝謝!
uj5u.com熱心網友回復:
使用 state 來維護所選收音機輸入的值。
我們向父元素添加一個偵聽器,以便我們可以使用事件委托,當它從子輸入元素捕獲更改事件時呼叫函式。當它被呼叫時,它檢查被點擊的元素是一個輸入(收音機),然后用它的值設定狀態。
該按鈕只是記錄當前狀態。
const { useState } = React;
function Example() {
// Initialise state
const [ radio, setRadio ] = useState(0);
// When the button is clicked log the current state
function handleClick(e) {
console.log(radio);
}
// When an element is clicked
function handleChange(e) {
// Grab the nodeName and value from
// the clicked element
const { nodeName, value } = e.target;
// Because we're using event delegation (attaching
// an event listener to a parent element and capturing
// events from child elements as they "bubble up" the DOM)
// we need to check to see if the clicked element is an input
if (nodeName === 'INPUT') {
// Set the state with the input value
setRadio(value);
}
}
return (
<div onChange={handleChange}>
<div className="form-check">
<input
type="radio"
className="form-check-input"
value={3}
name="priority"
/>
<label className="form-check-label">High Priority</label>
</div>
<div className="form-check">
<input
type="radio"
value={2}
className="form-check-input"
name="priority"
/>
<label className="form-check-label">Medium Priority</label>
</div>
<div className="form-check">
<input
type="radio"
value={1}
className="form-check-input"
name="priority"
/>
<label className="form-check-label">Low Priority</label>
</div>
<button onClick={handleClick}>Show radio state</button>
</div>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
button { margin-top: 0.5em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
uj5u.com熱心網友回復:
我在這里創建了演示,您可以將 onChange 方法添加到每個輸入,然后保存在狀態中。
演示: https : //codesandbox.io/s/tender-sinoussi-1t7fi?file=/ src/ App.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397216.html
標籤:javascript 反应 形式 输入 反应钩子
上一篇:滑動時如何不重繪螢屏
