只要 showSearch 状态为 true,就聚焦于搜索输入字段

问题描述 投票:0回答:1

每当状态 showSearch 状态为 true 时,我在尝试专注于输入字段时遇到问题。我正在使用 useRef 和 useEffect 来实现此目的。因此,每当 showSearch 标志发生变化时,我都会运行 useEffect 钩子来检查 showSearch 是否为 true,如果是,则它会使用 useRef 重点关注 HTML 元素引用。然而,它有问题,因为它不运行。

这是代码片段。

const [showSearch, setShowSearch] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
    console.log(showSearch);
    console.log(searchInputRef);

    if (showSearch && searchInputRef.current){
      searchInputRef.current.focus();
    }}, [showSearch]);



<form onSubmit={handleSubmit} style={{ width: "100%" }}>
                  <InputGroup size="lg">
                    <Input
                      variant="flushed"
                      placeholder="Search"
                      _placeholder={{
                        opacity: 1,
                        color: "gray.500",`your text`
                        fontSize: "1.5rem",
                      }}
                      _focus={{ borderColor: "whiteAlpha.800" }}
                      borderColor="#FFFFFF80"
                      pb={"1rem"}
                      fontSize="2rem"
                      onChange={handleSearchChange}
                      value={searchText}
                      ref={searchInputRef}.  // this is where i have referenced the HTML element.
                    />
                    <InputRightElement
                      w={["45%", "20%"]}
                      justifyContent={"flex-end"}
                    >
                      {searchText.length > 0 && (
                        <Button
                          size="sm"
                          onClick={handleClear}
                          bg={"transparent"}
                          color={"white"}
                          fontSize={"1.1rem"}
                          _hover={{ bg: "transparent" }}
                        >
                          Clear
                        </Button>
                      )}
                    </InputRightElement>
                  </InputGroup>
                </form>

如果您需要更多信息,请告诉我。 另外,我正在使用 chakra ui 作为 React 组件。

尝试使用 UseRef 和 useEffect,以便每次状态标志为 true 时,焦点都会更改为所需的输入元素。

javascript reactjs react-hooks frontend web-development-server
1个回答
1
投票

尝试这个解决方案:

import React, { useState, useRef, useEffect } from 'react';
import { Input, InputGroup, InputRightElement, Button } from "@chakra-ui/react";

const SearchComponent = () => {
  const [showSearch, setShowSearch] = useState(false);
  const searchInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    console.log('showSearch state:', showSearch);
    console.log('searchInputRef:', searchInputRef);

    if (showSearch && searchInputRef.current) {
      console.log('Focusing on search input');
      searchInputRef.current.focus();
    }
  }, [showSearch]);

  const handleSearchChange = (event) => {
    // Handle search input change
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    // Handle form submit
  };

  const handleClear = () => {
    // Handle clearing the search input
  };

  return (
    <form onSubmit={handleSubmit} style={{ width: "100%" }}>
      <InputGroup size="lg">
        <Input
          variant="flushed"
          placeholder="Search"
          _placeholder={{
            opacity: 1,
            color: "gray.500",
            fontSize: "1.5rem",
          }}
          _focus={{ borderColor: "whiteAlpha.800" }}
          borderColor="#FFFFFF80"
          pb={"1rem"}
          fontSize="2rem"
          onChange={handleSearchChange}
          value={searchText}
          ref={searchInputRef}
        />
        <InputRightElement
          w={["45%", "20%"]}
          justifyContent={"flex-end"}
        >
          {searchText.length > 0 && (
            <Button
              size="sm"
              onClick={handleClear}
              bg={"transparent"}
              color={"white"}
              fontSize={"1.1rem"}
              _hover={{ bg: "transparent" }}
            >
              Clear
            </Button>
          )}
        </InputRightElement>
      </InputGroup>
    </form>
  );
};

export default SearchComponent
© www.soinside.com 2019 - 2024. All rights reserved.