范围问题反应父子方法 ES6

Scoping issue react parent-child method ES6

我目前有点卡在下面。

function Tag(props){
    let {text, onRemove, key} = props;
    return (
        <span onClick={onRemove(key)} key={key}>{text}</span>
    )
}

function TagInput (props) {
    let {onChange, value, onKeyDown} = props;
    return (
        <input type="text" onChange={onChange} value={value} onKeyDown={onKeyDown} />
    )
}

class TagsInput extends Component {
    render() {
        let { Tag, TagInput, state } = this.props;
        console.log(state.tags);
        return (
            <div ref="div" onClick={(e) => this.handleClick(e)}>
                {state.tags.map((tag) =>
                    <Tag
                        text={tag.text}
                        key={tag.id}
                        onRemove={this.handleRemove}
                    />
                )}
                <TagInput
                    onChange={(e) => this.handleChange(e)}
                    onKeyDown={(e) => this.handleKeyDown(e)}
                />
            </div>
        )
    }

    handleClick(e) {
        console.log(e.target.value);
    }

    handleChange(e){
        //console.log(e.target.value);
    }

    handleKeyDown(e){
        //console.log('keycode', e.keyCode);
        const { dispatch } = this.props;
        if (e.keyCode === 32) {
            dispatch(addTag(e.target.value));
        }
        if (e.keyCode === 8 && e.target.value.length === 0) {
            dispatch(removeTag());
        }
    }

    handleRemove(id){
        const { dispatch } = this.props;
        dispatch(removeTag(id));
    }
}

TagsInput.propTypes = {
    TagInput: React.PropTypes.func,
    Tag: React.PropTypes.func,
    removeKeyCodes: React.PropTypes.array,
    addKeyCodes: React.PropTypes.array
};

TagsInput.defaultProps = {
    TagInput: TagInput,
    Tag: Tag,
    removeKeyCodes: [8],
    addKeyCodes: [9, 13]
};

我在控制台 Uncaught TypeError: Cannot read property 'props' of undefined 中从方法 handleRemoveconst { dispatch } = this.props 收到以下错误。这似乎是一个范围界定问题,但我似乎无法理解为什么会发生这种情况(没有双关语意,哈哈)。

您尝试过绑定 this 吗?尝试 this.handleRemove.bind(this, tag.id)tag.id 是你传递的参数,因为 handleRemove(id) 需要一个 id 作为参数。

ES6 classes 不会自动将 this 绑定到函数,扩展 Component 提供的函数除外,例如 componentDidMount 等..

from the docs

ES6 方式 - 将 this 绑定到构造函数中的方法,或调用它们的位置:

class TagsInput extends Component {
  constructor (props) {
    super(props)
    this.handleRremove = this.handleRemove.bind(this)
  }

  OR

  render() {
    return (
     <Tag   
       onRemove={this.handleRemove.bind(this)}
     />
  }

ES7 方式 #1:绑定语法

this.handleRemove = ::this.handleRemove

ES7 方式 #2:class 箭头函数(我认为这是最好的方式):

handleRemove = (id) => {
    const { dispatch } = this.props;
    dispatch(removeTag(id));
}

然后这样称呼它:

onRemove={ () => this.handleRemove(tag.id) }

更新:同时阅读@Road 的回答。在使用绑定方法时,您需要传递参数。