繁体   English   中英

JSX将此绑定到地图中的函数

[英]JSX binding this to a function within a map

我正在使用一个map函数,并已经测试并确认在maps函数中这可以根据需要引用类对象。

当我尝试通过将其绑定到jsx函数来再次传递它时,它并没有按照期望传递此信息。

错误:未捕获的类型错误:_this3.checkType(...)。bind不是函数

// wrapped in a class

checkType(type, options, placeholder, name, handleUpdatedValue, defvalue, index) {

        console.log(this);

        switch(type) {
            case 'select':
                return <select onChange={handleUpdatedValue.bind(this)} >{options.map((option, i) => <option value={option} key={i}>{option}</option>)}</select>
                break;
            case 'text':
                return <input onChange={handleUpdatedValue.bind(this)} name={name} placeholder={placeholder} type="text" />
                break;
            case 'date':
                return <input onChange={handleUpdatedValue.bind(this)} name={name} placeholder={placeholder} type="date" />
                break;
            default: 
                console.log('Error: Invalid Type');
        }
        return type === 'select' ? <select></select> : <input />
    }

return(
        <div className="formwrapper thinshadow">    
            <h3>{this.props.header}</h3>
            {this.getFields().map((field, i) => {
                <div key={i} className={field.classes}>
                    {this.checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index).bind(this)}

                                                                  // DOES NOT WORK ^

                    <div className="minilabel"></div>
                </div>
            }, this)}                                         // THIS WORKS

            <button className="btn btn-primary" 
                    onClick={() => this.props.onClick(values)} >
                    Save
            </button>
        </div>  
    );

您正在调用函数而不是绑定它。

this.checkType(field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index).bind(this)

应该

this.checkType.bind(this, field.type, field.options, field.placeholder, field.name, this.handleUpdatedValue.bind(this), field.defvalue, field.index)

bind用法

fun.bind(thisArg[, arg1[, arg2[, ...]]]

请参阅此链接以获取更多详细信息:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

编辑

您可以使用bind ,当你通过你的功能,另一个上下文(另一this差不多),而且还希望函数原下调用this

在您的情况下,您不需要绑定,因为在map ,您具有相同的this 使用forEach和map时,无需在React中绑定它

但是,如果您愿意,我强烈建议您在迭代时不要bind 您可以使用闭包,并在迭代之前bind

bind速度很慢 ,即使在大多数情况下它并不重要。 但更重要的是,您不想像forEachmap这样的迭代中进行bind ,因为在不知道(不使用React的情况下)很容易丢失上下文( this )。 然后您会挠头几个小时。

如果使用React,则可以bind render函数。

render: () {
  const checkType = this.checkType.bind(this);
  render (
    map((node) => { checkType(...) });
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM