使用onClick循环列表无法正常工作

时间:2018-12-11 09:57:17

标签: reactjs loops

我对ReactJ相当陌生,在遍历JavaScript数组方面确实存在一些问题。我设法没有错误地遍历它,但是当我在每个列表上使用onClick将remove按钮添加到removeSkill函数时,出现错误“ app.js:59097 Uncaught TypeError:无法读取未定义的属性'removeSkill'” < / p>

没有错误

const skillLists = this.state.skills.map(function(val){
                return <li>{val}</li>
            });

有错误

const skillLists = this.state.skills.map(function(val){
                return <li>{val} <button onClick={this.removeSkill}>x</button></li>
            });

完整代码

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Skills extends Component {
    constructor(props) {
        super(props);

        this.state = { 
            skills : ["Frost Bolt", "Arcane Missle"],
            skillField : ''
        };

        this.addSkill = this.addSkill.bind(this);
        this.removeSkill = this.removeSkill.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.clearField = this.clearField.bind(this);
    }

    clearField() {
        this.state.skillField = '';
    }

    handleChange(event) {
        this.setState({
            skillField : event.target.value
        });
    }

    addSkill() {
        this.state.skills.push(this.state.skillField);
        this.setState({
            skills: this.state.skills
        });
        console.log(this.state.skills);
        this.clearField();
    }

    removeSkill() {
        console.log("skillremoved");
    }

    render() {
        const skillLists = this.state.skills.map(function(val){
            return <li>{val} <button onClick={this.removeSkill}>x</button></li>
        });
        return (
            <div>
                <input onChange={this.handleChange} value={this.state.skillField} />
                <button onClick={this.addSkill}>Add Skill</button>
                <h4>Skills</h4>
                <ul>{skillLists}</ul>
            </div>
        );
    }
}

export default Skills;

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

问题是您没有使用箭头功能,因此丢失了对this的引用。

const skillLists = this.state.skills.map(function(val){
        return <li>{val} <button onClick={this.removeSkill}>x</button></li>
    });

尝试使用箭头功能

const skillLists = this.state.skills.map((val) => {
        return <li>{val} <button onClick={this.removeSkill}>x</button></li>
    });