构造函数中的 React 绑定方法 - 如何传入参数

React binding method in constructor - how to pass in Argument

我在 React 工作,阅读后 this article 我决定按照他们的建议在我的构造函数中切换事件处理程序的合并绑定。问题是,当我这样做时,我无法将表单变量传递给 onChange Material-UI 复选框函数。这是我的相关代码

client/prospect/ProspectForm.jsx

class ProspectForm extends React.Component {
  constructor(props) {
    super(props)
    // Bind Methods
    this.handleChangeProductType = this.handleChangeProductType.bind(this)

    this.state = {
    inquiryDate: moment().toDate(),
    productTypes: {list: [], other: '', },
    otherChecked: false,
    }
  }

  handleChangeProductType(a){
    console.log(a)
  }

  render() {
    return(
      <div className="field">
        { this.props.allProductTypes.map((referralSource, k) =>
        <Checkbox
          checked={this.checkProductType(referralSource)}
          onCheck={this.handleChangeProductType(referralSource)}
          label={referralSource}
          key={k} />
        )}
      </div>
    )
  }
}

export default createContainer(() => {

    const productTypes = [
      "Independent Living",
      "Memory Care",
      "Beauty Shop",
      "Skilled Nursing",
      "Therapy Rental",
    ]

  return {
    productTypes: productTypes,
  }
}, ProspectForm)

所以基本上,当我用这样的参数调用 onChange 时

this.handleChangeProductType(referralSource)

它实际上并没有调用该方法。当我这样称呼它时

onChange={this.handleChangeProductType}

它确实调用了该方法,但我无权访问函数中的 referralSource,我需要设置状态对象以便我可以跟踪哪些被检查并将它们与我的表单一起发送。那么我如何以一种可以在构造函数中设置使用绑定方法并将我的参数传递给该方法的方式来做到这一点呢?提前致谢

你可以这样写:

onCheck={(referralSource) => this.handleChangeProductType(referralSource)} 

不用担心构造函数中的bind。相反,您可以将其绑定在 onCheck 声明中并将 referralSource 参数传递给 bind.

onCheck={this.handleChangeProductType.bind(null, referralSource)}

您还可以为 <Checkbox /> 创建一个包装器组件,为您创建适当的 'loaded' 函数。

const ProductTypeCheckbox = ({
  referralSource,
  checkProductType,
  handleChangeProductType,
}) => {
  const isChecked = () => checkProductType(referralSource);
  const handleCheck = () => handleChangeProductType(referralSource);

  return (
    <Checkbox
      checked = { isChecked() }
      onCheck = { () => handleCheck() }
      label = { referralSource }
    />
  );
};

然后只需将上面列表中的 <Checkbox /> 替换为

<ProductTypeCheckbox
  key = { k }
  referralSource = { referralSource }
  checkProductType = { checkProductType }
  handleChangeProductType = { handleChangeProductType }
/>

这会产生一些开销,为循环中的每个项目创建一个新函数,但它是一个清晰的分离愚蠢和聪明的组件,并允许您轻松地读取在哪里设置的内容。