我已經使用redux-form創建了一個React組件,並且正在尋找第一個字段上的autoFocus。這些字段是通過循環一個對象併爲該對象中的每個項目創建一個字段來創建的。當我在JSX中使用autoFocus時,autoFocus在表單的最後一個字段(這是有道理的)。我可以使用循環創建的redux-form中的第一個字段自動對焦嗎?
有沒有人知道我如何可以在窗體的第一個字段autoFocus?
這裏是我的組件:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
class BalanceForm extends Component {
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
this.cancel = this.cancel.bind(this);
}
cancel() {
//not relevant
}
submitForm(e, values) {
//not relevant
}
render() {
return (
<div>
{this.props.balanceFormVisible &&
<div className="modal-background">
<div className="modal">
<form onSubmit={this.submitForm}>
{Object.keys(this.props.accounts).map((key) => {
return (
this.props.accounts[key].visible &&
<div key={this.props.accounts[key].name}>
<label className="form-label" htmlFor={this.props.accounts[key].name}>
{this.props.accounts[key].display}
</label>
<Field
name={this.props.accounts[key].name}
component="input"
type="number"
placeholder=""
autoFocus
/>
</div>
)
})}
<button type="submit">Submit</button>
<button onClick={ this.cancel } className="cancelbtn" >Cancel</button>
</form>
</div>
</div>
}
</div>
);
}
}
BalanceForm = reduxForm({form: 'balance'})(BalanceForm)
export default BalanceForm;
感謝提前:)
這可能會縮短嗎?我們不需要複製Field組件代碼。是這樣的: <字段 名稱= {this.props.accounts [鍵]。名稱} 成分= 「輸入」 類型= 「數字」 佔位符= 「」 {(I === 0)? autoFocus:「」} /> – TariqN
我確實嘗試過,但沒有編譯 – Sawdust
可能是,無論如何,你的解決方案看起來不錯。 (Y) – TariqN