【问题标题】:How do I filter a Bootstrap table based on a dropdown value in react如何根据反应中的下拉值过滤引导表
【发布时间】:2020-09-02 09:27:51
【问题描述】:

我在 react-bootstrap-table-next 库的基础上创建了一个表。我有一个下拉列表,我想用它来根据下拉列表中选择的值过滤数据。 以下是我所做的一些代码 sn-ps,按照我的代码顺序。

  1. 这就是我获取数据的方式

    useEffect(() => {
    const fetchData = async () => {
        try{
            const res = await axios.get('http://X.X.X.X:8000/api/statistic/');
            setstatistics(res.data);
            setloading(true);
        } catch (e) {
            console.log(e)
        }
    }
    fetchData();
    }, []);
    
  2. 这些是表格的列

    const columns = [
    {dataField: "id", text:"id number"},
    {dataField: "query_text", text:"query text"},
    {dataField: "period", text:"period"},
    {dataField: "value", text:"value"},
    {dataField: "total", text:"total"},
    {dataField: "ratio", text:"ratio"},
    

    ];

  3. 这是我正在使用的过滤器之一,如果根据句点的值过滤表格。

            <p>PERIOD</p>
            <select>
                {Array.from(new Set(statistics.map(obj => obj.period))).map(period => {
                    return <option value={period}>{period}</option>
                })}
            </select>
    
  4. 这就是我展示表格的方式

                 <BootstrapTable
                keyField="id"
                striped
                data={statistics}
                columns={columns}
                filter={filterFactory()}
                pagination={paginationFactory()}
                />
    

    如何根据上面“2”中的周期下拉选择来过滤数据,{statistics}?谢谢

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    您可以在state 中使用selectedValue 变量。每次更新下拉列表时:更新所选值。

    然后,当您渲染组件时,将 filterData 变量传递给列表,这将是您的 data 根据 selectedValue 过滤(只需使用 js filter() 方法)。

    • 带有类组件: 您需要在 render() 方法中为 filter 变量添加您的逻辑。

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          contacts: [
            {
              first_name: "Melloney",
              country: "Russia"
            },
            {
              first_name: "Fayre",
              country: "Russia"
            },
            {
              first_name: "Bernhard",
              country: "France"
            },
            {
              first_name: "Lauren",
              country: "China"
            },
            {
              first_name: "Terza",
              country: "China"
            }
          ],
          countries: ["All", "China", "Russia", "France"],
          countrySelected: "All"
        };
      }
    
      handleChange = e => {
        this.setState({ countrySelected: e.target.value });
      };
    
      componentDidMount() {
        this.setState({ filteredContacts: this.state.contacts });
      }
    
      render() {
        let filteredContacts = this.state.contacts;
    
        if (this.state.countrySelected !== "All") {
          filteredContacts = this.state.contacts.filter(
            contact => contact.country == this.state.countrySelected
          );
        }
    
        return (
          <div>
            <div>
              Countries : 
              &nbsp;<select onChange={e => this.handleChange(e)}>
                {this.state.countries.map(country => (
                  <option key={country} value={country}>
                    {country}
                  </option>
                ))}
              </select>
            </div>
            <table>
              <tr>
                <th>Name</th>
                <th>Country</th>
              </tr>
              {filteredContacts.map((contact, id) => (
                <tr key={id}>
                  <td>{contact.first_name}</td>
                  <td>{contact.country}</td>
                </tr>
              ))}
            </table>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    table {
      margin-top: 1em;
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    
    td, th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
    }
    
    tr:nth-child(even) {
      background-color: #dddddd;
    }
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <div id="root"></div>
    • 带有功能组件filterData 的逻辑将直接放入您的函数中,并相应地重新呈现。

    function App() {
        const [contacts, setContacts] = React.useState([{
          "first_name": "Melloney",
          "country": "Russia"
        }, {
          "first_name": "Fayre",
          "country": "Russia"
        }, {
          "first_name": "Bernhard",
          "country": "France"
        }, {
          "first_name": "Lauren",
          "country": "China"
        }, {
          "first_name": "Terza",
          "country": "China"
        }]);
        const [countries, setCountries] = React.useState(["All", "China", "Russia", "France"]);
        const [countrySelected, setSelected] = React.useState("All");
    
        const handleChange = e => {
          setSelected(e.target.value)
        }
    
        let filteredContacts = contacts;
        if (countrySelected !== "All") {
          filteredContacts = contacts.filter(contact => contact.country == countrySelected);
        }
    
        return (
            <div>
              <div className="header">
                Countries :
                <select
                    onChange={e => handleChange(e)}>
                  {countries.map(country =>
                      <option key={country} value={country}>{country}</option>
                  )}
                </select>
              </div>
              <table>
                <tr>
                  <th>Name</th>
                  <th>Country</th>
                </tr>
                {filteredContacts.map((contact, id) =>
                      <tr key={id}>
                        <td>{contact.first_name}</td>
                        <td>{contact.country}</td>
                      </tr>
                )}
              </table>
            </div>
        )
      }
      ReactDOM.render(<App/>, document.getElementById('root'))
    .header * {
      justify-content: center;
      font-size: 1em;
      margin: 1em;
    }
    
    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    
    td, th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 4px;
    }
    
    tr:nth-child(even) {
      background-color: #dddddd;
    }
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

    • 感谢您的回答,非常中肯!有没有办法我可以尝试使用函数组件?
    • @DerrickOmanwa 我更新了我的答案并添加了一个功能组件,如果它有效,你可以接受它!
    • 太棒了!非常感谢@A。 Ecrubit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2019-07-07
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多