reactjs - 在 React 中关注(滚动到)一个 DIV 元素

标签 reactjs

我有一个切换 DIV 元素,我想在它打开时关注(滚动到)它。

我关注了 doctabindex="-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 &&
...

最佳答案

因为只有当 formVisibletrue 时才会呈现您的表单,因此您需要等到您的组件重新呈现后才能尝试滚动到它。使用 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/

相关文章:

reactjs - 有人知道为什么我得到 'Uncaught Error in snapshot listener: FirebaseError: Missing or insufficient permissions' 吗?

reactjs - react : How to I get a React component button to lose focus?

audio - 是否有任何可替代htlm5音频标签的资源来进行响应?

reactjs - Material UI CardHeader 操作下拉列表

javascript - 对象字面值和 React.js

reactjs - 如何在 React/Redux/Typescript 通知消息中卸载、取消渲染或删除组件

javascript - 如何在 TypeScript 中将函数类型声明为参数

javascript - 在 Redux/React 中交换样本数据有哪些技巧?

javascript - 在同级 React 组件中更新和使用 redux 状态

forms - 无法在 redux-form w 中设置默认值。 react