【发布时间】:2019-01-31 09:58:13
【问题描述】:
我正在学习 React 和 Material-ui。
我想在一个组件中创建几个输入字段,这些字段的数量和值作为 props 从父组件接收。我添加了一个功能,可以在用户按下 Enter 按钮时移动焦点,或者在最后一个字段时创建新字段。
当前代码有 15 个引用(我知道这很愚蠢,但我认为不会超过 15 个)。问题是焦点在创建时不会移动到新字段。你能推荐一个更好的方法吗?
class ResponseInput extends Component {
componentWillMount() {
this.refs = [...Array(15)].map(r => React.createRef())
}
changeFocus = index => {
if (index < this.props.inputs.length - 1) {
this.refs[index + 1].current.focus();
} else {
this.props.addInput();
}
}
render() {
const { inputs, addInput, handleChangeInput } = this.props;
return (
<List>
{inputs.map((item, index) => (
<ListItem key={index} >
<Input
value={item}
inputRef={this.refs[index]}
onChange={(event) => handleChangeInput (index, event)}
onKeyPress= {(event) => {
if (event.key === 'Enter') {
this.changeFocus(index);
}
}}
// autoFocus
/>
</ListItem>
))}
</List>
);
}
}
【问题讨论】:
标签: reactjs material-ui