React子组件未在click事件上触发

时间:2015-12-17 12:34:57

标签: javascript reactjs react-jsx

我正在尝试创建标记建议输入字段。我试图理解为什么这段代码不起作用,因为它可以应用于任何数量的案例。

仅供参考:ReactComponent只是我实现的一个帮助器类,包含很少的方法,如_bind等。

class TagSuggestInput extends ReactComponent {
constructor(){
    super();
    this._bind('handleSelectionClick', 'handleRemoveTag', 'addNewTag', 'render');
    this.state = {
        suggestedOptions: [],
        tagListTo: []
    };
}

addNewTag(selectedIndex){
    var _this = this,
        tag= _this.state.suggestedOptions[selectedIndex].tag,
        tagList = _this.state.tagListTo;

    if($.inArray(email, tagList) == -1){
        _this.setState({tagListTO: tagList.push(tag)});
    }

}

handleRemoveTag(tag){
    var _this = this;

   // Remove tag code goes here. This is not the problem part
}

handleSelectionClick(selectedIndex, e){
    var _this = this;
    _this.addNewTag(selectedIndex);
    // other stuff here

}

render() {
    var _this = this;
    return (
        <div className="tagitos">
            {_this.state.tagListTo.map(function(item, index){
                return  (
                    <span key={index} >
                        <Tag data={item} onRemove={_this.handleRemoveTag.bind(_this)} />
                    </span>
                );
            })}
            <input className="tag-input" ref="input"></input>
            <ul>
                {_this.state.suggestedOptions.map(function(item, index){
                    return  (
                        <li key={index}
                            onClick={_this.handleSelectionClick.bind(_this, index)}
                        >
                            <OptionComponent data={item} index={index}/>
                        </li>    
                    );
                })}  
            </ul>
        </div>          
    );
}
}

子组件

class Tag extends ReactComponent{
constructor(){
    super();
    this._bind('render', 'removeFromList');
}

removeFromList(tag){
    var _this = this;

    _this.props.onRemove(tag);
}

render(){
    var _this = this;
    return(
        <span className="tag-element">
            <div>{_this.props.data}</div>
            <div onClick={_this.removeFromList(_this.props.data)} className="tag-closeButton">&times;</div>
        </span>  
    );
}
}

我想通过单击标签X按钮而不是标签本身来删除标签,否则我可能只是像在选项中那样在父范围内创建了整个代码。

工作流程:选项从后端生成,作为自动填充,列在父级的输入字段下方。选择选项后,它会生成标记。到目前为止一切都很好!

但是:自动调用删除标记的代码并尝试删除它。由于我已将其删除,因此标签仍保留,但“X&#39; X&#39;单击。好像onCLick事件没有绑定。

未调用函数 removeFromList ,但在将组件添加到视图时会调用它。为什么?怎么预防这个?我的猜测是,通过解决这个问题,我也可以解决onClick问题。

1 个答案:

答案 0 :(得分:2)

它不起作用,因为你没有将函数绑定到onclick。您只在每次渲染时运行一次 你可以写这样的东西

removeFromList(){
    var _this = this;
    var tag = _this.props.data;
    _this.props.onRemove(tag);
}

...

 <div onClick={_this.removeFromList}></div>
相关问题