在渲染组件后,将焦点设置在特定文本字段上的反应方式是什么?
文档似乎建议使用refs,例如:
ref="nameInput"在渲染函数的输入字段中设置,然后调用:
this.refs.nameInput.getInputDOMNode().focus();
Run Code Online (Sandbox Code Playgroud)
但我应该在哪里打电话呢?我尝试了几个地方,但我无法让它工作.
我在我的应用程序中使用Redux,在组件内部我希望在商店发生更改时滚动到特定的div标签.我有Redux部分工作,所以它触发componentDidUpdate()方法(我已经路由到这个compoennt视图).据我所知,问题是方法scrollIntoView()无法正常工作cos componentDidUpdate()有一个默认行为,滚动到顶部覆盖scrollIntoView().为了解决这个问题,我在setTimeout中包含了调用scrollIntoView()的函数,以确保不会发生这种情况.我想做的是调用一个preventDefault()或任何其他更优雅的解决方案,但我无法找到触发'scrollTop'事件的位置,我在这里查看了Doc:https://facebook.github. io/react/docs/react-component.html#componentdidupdate 和此函数中传递的参数是componentDidUpdate(prevProps,prevState),因为没有事件我不知道如何调用preventDefault()
我已经按照这个文档:https ://facebook.github.io/react/docs/refs-and-the-dom.html并尝试了人们在这里建议的不同方法:如何滚动div以在ReactJS中可见?
没有什么工作虽然这是我的代码,如果有人有任何提示,谢谢
class PhotoContainer extends React.Component {
componentDidUpdate(){
setTimeout(() => {
this.focusDiv();
}, 500);
}
focusDiv(){
var scrolling = this.theDiv;
scrolling.scrollIntoView();
}
render() {
const totalList = [];
for(let i = 0; i < 300; i += 1) {
totalList.push(
<div key={i}>{`hello ${i}`}</div>
);
}
return (
<div >
{totalList}
<div ref={(el) => this.theDiv = el}>this is the div I'm trying to scroll to</div>
</div>
)
Run Code Online (Sandbox Code Playgroud)
}; }
在阅读了React set focus和React focus with timeout之后,我仍然有点困惑什么是设置focus输入的正确跨浏览器选项。
我遇到了条件渲染输入的问题,这些输入在渲染后可能具有焦点table,其中input放置在 中td。
1)使用componentDidUpdate的解决方案:
//...
componentDidUpdate() {
this.input && this.input.focus();
}
render() {
const show = this.state.isShown;
return (
<td className="editable">
{!show ? (
<input
type="number"
ref={(input) => { this.input = input }}
value={this.state.value}
onBlur={this.save}
onKeyPress={e =>
e.which === 13 || e.keyCode === 13 ? this.save() : null}
/>
) : (
<span onClick={this.onTdClick}>{this.props.name}</span>
)}
</td>
);
}
Run Code Online (Sandbox Code Playgroud)
此解决方案适用于 Chrome、IE11、Edge,但不适用于最新的 Firefox( …