我如何在 React 的 ref 上调用 scrollIntoView

How can I call scrollIntoView on an ref in React

当我调用 someFun 时,我想让 formRef 在屏幕上可见(它在页面的顶部,当我调用 someFun 时我可能已经滚动到底部),有没有标准的方法可以做到这一点?

function List(props) {

    const formRef = useRef(null);


    const someFun = params => {

        if (formRef && formRef.current) {
      

          //error FormRef.current.scrollIntoView is not a function
          formRef.current.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'start' });
        }
    }
}


这是上面父组件中使用的表单组件: 它是一个 Ant 设计表单组件: link 在这里 https://3x.ant.design/components/form/#header

import { Form, Icon, Input, Button, Checkbox } from 'antd';

class NormalLoginForm extends React.Component {
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <Form.Item>
          {getFieldDecorator('username', {
            rules: [{ required: true, message: 'Please input your username!' }],
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="Username"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: 'Please input your Password!' }],
          })(
            <Input
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="Password"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('remember', {
            valuePropName: 'checked',
            initialValue: true,
          })(<Checkbox>Remember me</Checkbox>)}
          <a className="login-form-forgot" href="">
            Forgot password
          </a>
          <Button type="primary" htmlType="submit" className="login-form-button">
            Log in
          </Button>
          Or <a href="">register now!</a>
        </Form.Item>
      </Form>
    );
  }
}

const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(NormalLoginForm);

ReactDOM.render(<WrappedNormalLoginForm />, mountNode);

这是如何将引用从 NormalLoginForm 传递到 List 组件。

在您的列表组件中,您需要使用 forwardRef,因为它为子组件提供了对其父组件

创建的 DOM 元素的引用

例子

应用程序

import "./styles.css";
import List from "./List";
import { useRef } from "react";

export default function App() {
  const targetElement = useRef();
  const scrollingTop = (event) => {
    const elmnt = targetElement;
    elmnt.current.scrollIntoView({
      behavior: "smooth",
      block: "center",
      inline: "start"
    });
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>lorem ipsum </p>
      <div style={{ height: "200vh", backgroundColor: "orange" }}>
        <h1>Example Form Tag </h1>
        <button id="btnAppear" onClick={scrollingTop}>
          Submit Scroll bottom
        </button>
      </div>
      <List ref={targetElement} />
    </div>
  );
}

列表

import { forwardRef } from "react";
const List = (ref) => {
  return (
    <div
      style={{
        backgroundColor: "purple",
        paddingTop: "50px",
        color: "white"
      }}
      ref={ref}
    >
      <h1>List View</h1>
    </div>
  );
};

export default forwardRef(List);

DEMO