set class using state if else with react 获取未定义错误状态

set class using state if else with react gets state of undefined error

我正在尝试根据发送到组件的专业人士动态设置 class。不知何故我收到错误“无法读取未定义的 属性 'state'”。 我想当我尝试将状态的 class 设置为 class 时,这并不存在?在组件渲染中使用它之前是否必须重新绑定它?

var ReactDOM = require('react-dom');
var React = require('react');

class Button extends React.Component {
    constructor(props) {
        super(props);
        console.log("BUTTON")
        console.log(props);

        this.state = {
            class: "small-button"
        };

        props.options.map(function (option) {
            if (option.Description > 10) {
                this.setState({
                    class: "big-button"
                });
            }
        });
        console.log("STATE: " + this.state.class);
    }

    render() {
        if (this.props.options) {
            return (<div> {
                this.props.options.map(function (option) {
                    return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
                })
            }
            </div>
            )
        } else {
            return <div>No options defined</div>
        }
    }
}

module.exports = Button;

这是一个绑定问题,您需要 bind 函数在其中使用 this 关键字(正确的上下文)。

使用这个:

render() {
        if (this.props.options) {
            return (<div> {
                this.props.options.map((option) => {
                    return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
                })
            }
            </div> )
        } else {
            return <div>No options defined</div>
        }
    }

查看此答案以获取有关 arrow function and this keyword

的更多详细信息

一个建议:不要把逻辑放在constructor里面,也不要setState,使用生命周期方法。将该逻辑放在 componentDidMount 方法或 componentWillMount 方法中。

像这样:

class Button extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            class: "small-button"
        };
    }

    componentDidMount(){
        this.props.options.forEach((option) => {
            if (option.Description > 10) {
                this.setState({
                    class: "big-button"
                });
            }
        });
    }

    render() {
        if (this.props.options) {
            return (
                <div> 
                {
                    this.props.options.map((option) => {
                        return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div>
                    })
                }
                </div>
            )
        }else{
            return <div>No options defined</div>
        }
    }
}