[英]How do i connect 2 input boxes to a single function in react
> weightCalc(event) { console.log(event) }
>
> render() {
> return (
> <div>
>
>
>
>
>
> <label>
> Stones
>
> <input type="textbox" name="test" onChange={this.weightCalc}/>
> </label>
>
> <label>
> Pounds <input type="textbox" name="test2" onChange={this.weightCalc} />
> </label>
我希望能夠將一個 function 與 2 個輸入的值一起使用,然后請更新 state
這將使您根據輸入字段的名稱進行更新,但它們應該與 state 中的鍵值匹配,以使用特定值更新/同步它們。
weightCalc(event) { this.setState({ [event.target.name]: event.target.value }); }
render() {
return (
<div>
<label>
Stones
<input type="textbox" name="test" onChange={this.weightCalc} value={this.state.test}/>
</label>
<label>
Pounds <input type="textbox" name="test2" onChange={this.weightCalc} value={this.state.test2} />
</label>
weightCalc(type, amount) {
// type === 'pounds' ? do something with pounds : do something with stones
}
render() {
return (
<div>
<label>Stones </label>
<input type="textbox" name="test" onChange={(e) => this.weightCalc('stones', e.target.value)}/>
<label>Pounds</label>
<input type="textbox" name="test2" onChange={(e) => this.weightCalc('pounds', e.target.value)} />
)
}
在onChange
處理程序中,您傳入哪種類型的更新(石頭或磅),然后是在e.target.value
中找到的值。 在 function 中,您在繼續之前檢查哪種類型。
我贊成 Abdulrahmam 的回答,這個回答非常簡潔明了。 我的是另一種處理數據的方式。 有時您的輸入數量會變得很大,為了避免沖突,命名可能會變得很時髦。 為了防止這種情況,您可以顯式傳入字符串(或者更好的是在某處以常量定義的字符串)。 這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.