1

我正在尝试映射状态数组并在用户填写输入后添加输入字段,如果任何输入为 '' 或 null 或者任何字段与模式字符串不匹配,那么我想滚动页面到该错误字段,以便用户收到有关错误字段的通知

如何滚动页面到该元素提前谢谢

import { Container, TextField, Button } from "@material-ui/core";
import React, { Component } from "react";

class Home extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [
        { product_name: "", product_price: "", product_qty: "" },
        { product_name: "", product_price: "", product_qty: "" },
        { product_name: "", product_price: "", product_qty: "" },
      ],
    };
  }

  changeHandler(eventValue, index, action) {
    if (action === "p_name") {
      //updating value
    } else if (action === "price") {
      //updating value
    } else if (action === "qty") {
      //updating value
    }
  }

  saveData() {
    //check if any fields contains "" value
    //if null found then scroll to that field
  }

  render() {
    return (
      <div>
        {this.state.data.map((field, key) => {
          return (
            <Container key={key}>
              <TextField
                fullWidth
                id="outlined-basic"
                label="Product Name"
                onChange={(e) =>
                  this.changeHandler(e.target.value, key, "p_name")
                }
                value={field.product_name}
                variant="outlined"
              />
              <TextField
                fullWidth
                id="outlined-basic"
                label="Product Price"
                onChange={(e) =>
                  this.changeHandler(e.target.value, key, "price")
                }
                value={field.product_price}
                variant="outlined"
              />
              <TextField
                fullWidth
                id="outlined-basic"
                label="Product Qty"
                onChange={(e) => this.changeHandler(e.target.value, key, "qty")}
                value={field.product_qty}
                variant="outlined"
              />
            </Container>
          );
        })}

        <Button onClick={this.saveData}>Save</Button>
      </div>
    );
  }
}

export default Home;
4

1 回答 1

0

使用钩子,而不是类,它将使您的代码更短且更易于阅读。在这里,您可以简单地将 ref 传递给锚元素,并添加一个事件侦听器,以便在捕获错误时使窗口平滑滚动到它。就像是:

function Foo(){
  const ref = useRef(null);
  useEffect(() => {
    if (error) {
      ref.current?.scrollIntoView({behavior: "smooth"});
    }
  }, [error, ref]);
  
  return (
   <>
    <input ref={ref}>
   </>
   )
  }
  

于 2021-02-08T09:03:40.580 回答