作用域问题反应父子方法ES6

Scoping issue react parent-child method ES6

本文关键字:子方法 ES6 父子 问题 作用域      更新时间:2023-09-26

我目前有点拘泥于以下内容。

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行得到以下错误。这似乎是一个范围界定问题,但我似乎无法理解为什么会发生这种情况(并非双关语lol)。

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

来自文档

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:类箭头函数(我认为这是最好的方法):

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

然后称之为:

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

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

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