我有一个带有“是/否”问题界面的 react 应用程序。我正在使用 redux 来管理状态。
该应用程序提供了一系列动态添加的输入字段。
当使用'y'或'n'按键回答问题时,我希望系列中的下一个输入自动获得焦点 - 实现快速数据-入口。事实证明这非常困难!
我的 redux 存储包含当前问题的索引 - 我希望将其转化为对该输入的关注。
/*Input Component*/
const quizQs = ({
questionArray = ["Q1", "Q2", "Q3", "Q4"]
currentQIndex, //From Store
changeQIndex, //Action
}) => {
const _handleKeyDown = (e) => {
if(e.key == 'y' || e.key == 'n'){
//Dispatches Action that increases current currentQIndex'
}
}
//_handleFocus()... for updating currentQIndex if an input is focused by the user
return (
{questionArray.map((q, index) => {
return(
<input
key={index}
onKeyDown={_handleKeyDown}
onFocus={_handleFocus}
type="text"
placeholder={q}
/>
)
})}
)
}
/*Main Component -- Connected to Store*/
class myQuiz extends React.Component {
constructor(props){
super(props);
}
render(){
return(
<div>
<quizQs
currentQIndex = {this.props.currentQIndex}
changeQIndex = {this.props.changeQIndex}
/>
</div>
)}
}
我尝试过设置autoFocus = true
,如果商店的 'currentQIndex'
与 'quizQs'
中该特定问题的索引匹配成分。该方法能够在页面首次渲染时聚焦指定字段,但当'currentQIndex'
时焦点不会改变。商店的变化。
当我寻找答案时,React 'refs'
+ 使用回调似乎是可行的方法( https://reactjs.org/docs/refs-and-the-dom.html#the-ref-callback-attribute ),但我不知道如何设置这样的 'focus'
回调,响应 Redux 存储中的更改。
另外,为了使用Refs
,组件必须设置为类,而不是箭头函数。 AFAIK,在一个文件中包含多个类并不是一种好的做法,而且将如此多的不同组件连接到一个 redux 存储似乎也不合适。
非常感谢您的帮助。
最佳答案
这是您想要实现的目标的简单示例:https://codesandbox.io/s/z64qw3nkzx
我稍微简化了它,但重点就在那里。
由于 .focus()
是 DOM 元素上的 native 方法,因此您需要一种跟踪这些输入元素的方法。在 React 中,有 ref 属性。它接受一个函数,该函数有一个参数,该参数是组件的实际 DOM 元素。
您会看到我将所有 DOM 引用放入一个数组中:
<input
ref={el => this.questionInputElements[index] = el}
key={index}
// all other props
/>
按向上键*查找数组中的下一个元素并将其聚焦:
const nextInput = this.questionInputElements[index + 1];
if (nextInput) {
nextInput.focus();
}
* 它需要按下键(而不是按下键),因为它将聚焦之前的下一个字段并在下一个输入中打印 y/n。尝试一下很有趣:)
关于javascript - react + Redux : Changing input focus programatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46633738/