You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两个下拉筛选器绑定到单个搜索按钮实现点击筛选

实现点击按钮触发筛选的解决方案

没问题,我帮你调整代码实现点击按钮才触发筛选的功能。核心思路是让下拉框只暂存选中的筛选条件,等到点击搜索按钮时再执行过滤逻辑,把结果更新到状态里用于渲染,这样就不会实时触发筛选了。

下面是修改后的完整代码,我会标注关键修改点:

constructor(props) {
  super(props);
  this.state = {
    developers: [],
    filteredDevelopers: [], // 新增:存储过滤后的结果
    filterCountry: "All locations",
    filterSkills: "All skills"
  };
}

componentDidMount() {
  fetch('API')
    .then(features => features.json())
    .then(developers => {
      this.setState({ 
        developers,
        filteredDevelopers: developers.features || [] // 初始时把全部数据赋值给过滤结果
      })
    })
}

filterCountry(e){
  this.setState({filterCountry: e })
}

filterSkills(e){
  this.setState({filterSkills: e })
}

// 新增:搜索按钮点击时执行的过滤逻辑
handleSearch = () => {
  const { developers, filterCountry, filterSkills } = this.state;
  let result = developers.features || [];

  if (filterCountry && filterSkills) {
    // 执行国家筛选
    result = result.filter(developer => {
      return filterCountry === 'All locations' || developer.properties.continent.includes(filterCountry)
    });
    // 执行技能筛选
    result = result.filter(developer => {
      return filterSkills === 'All skills' || developer.properties.skills.includes(filterSkills)
    });
  }

  // 更新过滤后的结果到状态
  this.setState({ filteredDevelopers: result });
}

render() {
  const { filteredDevelopers } = this.state;

  if (!filteredDevelopers){
    return null
  }

  return (
    <div>
      <div>
        <ControlSelect 
          onChange={this.filterCountry.bind(this)} 
          value={this.state.filterCountry} 
          options={options_dd1} 
        />
      </div>
      <div className="inline-block mr24">
        <ControlSelect 
          onChange={this.filterSkills.bind(this)} 
          value={this.state.filterSkills} 
          options={options_dd2} 
        />
      </div>
      {/* 绑定点击事件到新增的handleSearch方法 */}
      <button onClick={this.handleSearch}>Search</button>
      
      <div>
        {filteredDevelopers.map(developer => {
          return (
            <div key={developer.id}>
              {developer.properties.name}
              {developer.properties.description}
              {developer.properties.skills}
            </div>
          )
        })}
      </div>
    </div>
  )
}

关键修改说明:

  1. 新增状态filteredDevelopers:专门用来存储点击搜索后过滤好的开发者数据,初始时和原始数据保持一致,保证页面加载时显示全部内容。
  2. 新增handleSearch方法:把原来render里的过滤逻辑移到这里,只有点击按钮时才执行,并将结果更新到filteredDevelopers状态中。
  3. 按钮绑定点击事件:给搜索按钮加上onClick={this.handleSearch},触发过滤逻辑。
  4. 渲染逻辑简化:render里直接使用filteredDevelopers来渲染列表,不用每次都重复执行过滤,既实现了需求,也优化了一点性能。

这样调整后,下拉框选择选项时只会更新筛选条件的状态,不会立刻过滤结果,只有点击搜索按钮后才会更新显示的内容,完全符合你的需求~

内容的提问来源于stack exchange,提问作者tallgirltaadaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:09:47