我有一个切换 DIV 元素,我想在它打开时关注(滚动到)它。
我关注了 doc与 tabindex="-1"
一起无效。
class App extends Component {
constructor(props) {
super(props);
this.state = {
formVisible: false
}
this.formRef = React.createRef();
this.onReply = this.onReply.bind(this);
}
onReply(e) {
this.formRef.current.focus(); // doesn't have any effect
this.setState({formVisible: true});
}
render() {
return (
<div>
<div>
<a onClick={this.onReply} href="#">Reply</a>
</div>
<div>
....
</div>
<div ref={this.formRef} tabindex="-1">
{this.state.formVisible &&
<form>
...
</form>
}
</div>
</div>
);
}
}
到目前为止我使用的是 anchor ,但我觉得这个解决方案不是很优雅...
...
<a onClick={this.onReply} href="#form">Reply</a>
...
<a name="form"></a>
{this.state.formVisible &&
...
anchor 方法的另一个问题是,当页面上有更多动态创建的元素时。然后我必须为 anchor 使用某种 ID,这非常复杂:
const {id} = this.props.data;
...
<a onClick={this.onReply} href={"#form-" + id}>Reply</a>
...
<a name={"form-" + id}></a>
{this.state.formVisible &&
...
最佳答案
因为只有当 formVisible
为 true
时才会呈现您的表单,因此您需要等到您的组件重新呈现后才能尝试滚动到它。使用 componentDidUpdate
结合 scrollIntoView
:
componentDidUpdate(prevProps) {
// `formVisible` went from false -> true, scroll the <form> into view
if (!prevProps.formVisible && this.props.formVisible) {
this.formRef.current.scrollIntoView();
}
}
关于reactjs - 在 React 中关注(滚动到)一个 DIV 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54960096/