javascript - 为什么在 reactjs 组件方法中未定义

标签 javascript reactjs

我有一个使用 react-autosuggest 的简单搜索栏。当我创建建议时,我想附加一个 onClick 处理程序。这个onClick是从一个父类传下来的。但是,当呈现建议时,this 未定义,因此未附加点击处理程序。

我附加了下面的组件,不起作用的逻辑在 renderSuggestion 方法中。

import Autosuggest from 'react-autosuggest'
import React from 'react'


export class SearchBar extends React.Component {
     static getSuggestionValue(suggestion) {
        return suggestion;
    }


    static escapeRegexCharacters(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    constructor(props) {
        super(props);

        this.state = {
            value: '',
            suggestions: [],
            listOfValues: this.props.tickers
        };

    }

    onChange = (event, { newValue, method }) => {
        this.setState({
            value: newValue
        });
    };

    onSuggestionsFetchRequested = ({ value }) => {
        this.setState({
            suggestions: this.getSuggestions(value)
        });
    };

    onSuggestionsClearRequested = () => {
        this.setState({
            suggestions: []
        });
    };

    renderSuggestion(suggestion) {
        return (
            <span onClick={() => this.props.clickHandler(suggestion)}>{suggestion}</span>
        );
    }



    getSuggestions(value) {
        const escapedValue = SearchBar.escapeRegexCharacters(value.trim());

        if (escapedValue === '') {
            return [];
        }

        const regex = new RegExp('^' + escapedValue, 'i');

        return this.state.listOfValues.filter(ticker => regex.test(ticker));
    }



    render() {
        const { value, suggestions } = this.state;
        const inputProps = {
            placeholder: "Search for stocks...",
            value,
            onChange: this.onChange
        };

        return (
            <Autosuggest
                suggestions={suggestions}
                onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
                onSuggestionsClearRequested={this.onSuggestionsClearRequested}
                getSuggestionValue={SearchBar.getSuggestionValue}
                renderSuggestion={this.renderSuggestion}
                inputProps={inputProps} />
        );
    }
}

最佳答案

这是因为您需要将“this”绑定(bind)到您的函数。 如果将此代码添加到构造函数中

constructor(props) {
    super(props);

    this.state = {
        value: '',
        suggestions: [],
        listOfValues: this.props.tickers
    };
    //this line of code binds this to your function so you can use it
    this.renderSuggestion = this.renderSuggestion.bind(this);

}

它应该可以工作。更多信息可以在 https://reactjs.org/docs/handling-events.html 找到

关于javascript - 为什么在 reactjs 组件方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49428216/

相关文章:

javascript - jQuery REST Session 不起作用,但在 POSTMan 中有效

javascript - 如何使用 gatsby-image 添加内联图像?

javascript - 如何在 enzyme 测试中访问由 dangerouslySetInnerHTML 创建的实际呈现的 HTML

javascript - 我刚刚添加了 var React = require ('react-native' );我的整个构建失败了

javascript - 如何使用 jQuery 定位表中同一行上的另一个元素

javascript - 简单的 JavaScript/Bootstrap 下拉问题

javascript - WebKit 中带有滚轮的生涩视差

javascript - React 钩子(Hook)需要返回一个值吗?

javascript - 下拉菜单无法在 React 中实现

javascript - 'innerHTML'和 'appendChild'的区别