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

时间:2018-03-22 12:03:00

标签: 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} />
        );
    }
}

2 个答案:

答案 0 :(得分:3)

这是因为你需要绑定&#34;这个&#34;你的功能。 如果将此代码添加到构造函数

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

找到

答案 1 :(得分:1)

renderSuggestion的范围内,this不是指类的实例。

renderSuggestion转换为箭头函数,就像您在其他地方所做的那样,将确保this引用该类的实例。

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