Saw*_*ust 5 forms focus autofocus reactjs redux-form
我已经使用 redux-form 创建了一个 React 组件,并且希望在第一个字段上自动聚焦。这些字段是通过循环遍历一个对象并为该对象中的每个项目创建一个字段来创建的。当我在 JSX 中使用 autoFocus 时,表单中的最后一个字段是 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;
Run Code Online (Sandbox Code Playgroud)
提前致谢 :)
解决方案是有条件地呈现表单字段。感谢亚历山大鲍罗丁的灵感......
{Object.keys(this.props.accounts).map((key, i) => {
console.log(key, i)
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>
{(i === 0) ? (
<Field
name={this.props.accounts[key].name}
component="input"
type="number"
placeholder=""
autoFocus
/>
) : (
<Field
name={this.props.accounts[key].name}
component="input"
type="number"
placeholder=""
/>
)}
</div>
)
})}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3729 次 |
最近记录: |