如何在Reaction中将道具传递给另一个组件?

因此,我在第一列中有一个带有搜索筛选器onPressEnter的表组件,并且我希望我的搜索栏组件基本上执行相同的操作。

在我的Table.js中,我要将confirm()传递给Searchbar.js

const columns = [
    {
      key: "1",
      title: "Title",
      dataIndex: "title",
      render: (text) => <a href="/">{text}</a>,
      sorter: (record1, record2) => record1.title.localeCompare(record2.title),
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm }) => {
        return (
          <Input
            autoFocus
            placeholder="Search Column..."
            value={selectedKeys[0]}
            onChange={(e) => {
              setSelectedKeys(e.target.value ? [e.target.value] : []);
            }}
            onPressEnter={() => {
              confirm();
            }}
            onBlur={() => {
              confirm();
            }}
          ></Input>
        );
      },
      filterIcon: () => {
        return <SearchOutlined />;
      },
      onFilter: (value, record) => {
        return record.title.toLowerCase().includes(value.toLowerCase());
      }
    },]

这是我的Searchbar.js

function Searchbar() {
  return (
    <div>
      <Form className="d-flex align-items-start">
        <Form.Control
          type="search"
          placeholder="Enter a keyword or a company name..."
        />
        <Button>Search</Button>
      </Form>
    </div>
  );
}

export default Searchbar;

我还制作了一个codesandboxproject,以便更好地可视化我的问题。所以我有一个主搜索栏组件,我希望它与我的表组件中的搜索筛选器做同样的事情。这有可能吗?如果是这样,那么解决这一问题的最佳方式是什么?我很感激你们的帮助。谢谢!


解决方案

我建议使用重构。将数据和搜索逻辑向上移动到父组件,并将其作为道具传递给子组件,如下所示:

import React, { useState, useEffect } from "react";
import Searchbar from "../components/Searchbar";
import MyTable from "../components/Table";

export default function HomeAfterSearch() {
  const [data, setData] = useState([]);
  const [searchText, setSearchText] = useState("");
  const [loading, setLoading] = useState(true);

  const getData = () => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => response.json())
      .then((data) => {
        setData(data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <div className="App">
      <Searchbar searchText={searchText} setSearchText={setSearchText} />
      <MyTable
        searchText={searchText}
        setSearchText={setSearchText}
        data={data.filter((item) => {
          if (!searchText) return true;
          else if (
            JSON.stringify(item)
              .toLowerCase()
              .includes(searchText.toLowerCase())
          )
            return true;
          else return false;
        })}
      />
    </div>
  );
}

那么在MyTable中,您可以这样声明它:

function MyTable(props) {
const { data, loading } = props;
.....

SearchBar如下:

function Searchbar(props) {
const { searchText, setSearchText } = props;

相关文章