简体   繁体   English

出于某种原因映射 onClick 事件后<li>不会工作</li>

[英]For some reason after mapping onClick event on <li> won't work

I'm trying to make a search field with a dropdown list.For some reason, after mapping over an array and making a list of a few "li" the onClick handler sends to suggestionSelected (value) function 3 values without even clicking on any of them!我正在尝试使用下拉列表创建一个搜索字段。出于某种原因,在映射到一个数组并列出几个“li”之后,onClick 处理程序发送到 suggestionSelected (value) function 3 个值,甚至没有点击任何他们中的!

I'm enclosing the screenshot depicting my attempts to enter the name of a city starting with "s".我附上了描述我尝试输入以“s”开头的城市名称的屏幕截图。 See the output in the console.在控制台看到output。

The piece of code in question is commented.有问题的代码段被注释了。

import React from 'react';
import shortid from 'shortid';
import modules from './CityForm.module.css';


export default class ToDoForm extends React.Component {
  state = {
    text: '',
    items: ["Moscow", "Saratov", "Singapore", "New York"],
    suggestions: []
  };

  handleChange = (event) => {
    this.setState({
      text: event.target.value
    });

    const value = event.target.value;
    let suggestions = [];
    if (value.length > 0) {
      const regex = new RegExp(`^${value}`, 'i');
      suggestions = this.state.items.sort().filter(v => regex.test(v));
    }
    this.setState({
      suggestions: suggestions
    });
  }

  renderSuggestions() {
    const { suggestions } = this.state;
    if (suggestions.length === 0) {
      return null;
    } else {
      return (
        <ul className={modules.dropdown_list}>
          {suggestions.map((item) => <li onClick={this.suggestionSelected(item)}> {item} </li>)}
        </ul>
      )
    }
  }

  handleSubmit = (event) => {
    event.preventDefault();
    this.props.onSubmit({
      id: shortid.generate(),
      text: this.state.text
    });
    this.setState({
      text: ''
    });
  }

  suggestionSelected(value) {
    console.log(value);
    // this.setState({
    //  text: value,
    //  suggestions: []
    // });
  }

  render() {

    const { items } = this.state;

    return (

      <form
        className={modules.search_row}
        onSubmit={this.handleSubmit}>
        <div>
          <input
            autoComplete="off"
            className={modules.input}
            name={modules.text}
            value={this.state.text}
            onChange={this.handleChange}
            placeholder="E.g. Moscow..."
            onKeyUp={this.filterOptions}
          />
          {this.renderSuggestions()}
        </div>
        <button
          className={modules.addcity_btn}
          onClick={this.handleSubmit}>
          Add city
                </button>
      </form>

    )
  }
}

在此处输入图像描述

try change your image function call to尝试将您的图像 function 调用更改为

  { suggestions.map((item) => <li onClick={() => this.suggestionSelected(item)}> {item} </li> ) }

by passing it as onClick={this.suggestionSelected(item)} , it is actually calling the function this.suggestionSelected(item) when rendering通过将其作为onClick={this.suggestionSelected(item)}传递,它实际上是在渲染时调用 function this.suggestionSelected(item)

if you wish to pass something back as a parameter in a callback assignment itself, pass it as a function reference如果您希望在回调分配本身中将某些内容作为参数传回,请将其作为 function 引用传递

onClick={() => this.suggestionSelected(item)}

Wrong: <li onClick={this.suggestionSelected(item)}>错误: <li onClick={this.suggestionSelected(item)}>

Correct: <li onclick={(evt)=>this.suggestionSelected(item) }正确: <li onclick={(evt)=>this.suggestionSelected(item) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM