我有一些功能需要在多个组件中使用,所以我将它们放在这样的模块中。
export default class FormFunctions {
handleChange (event) {
const changedOne = event.target.name
const newValue = event.target.value
const newState = {}
newState[changedOne] = newValue
this.setState(newState)
}
handleSubmit (infoToPass, toThisMethod) {
Meteor.call(toThisMethod, infoToPass, function () {
console.log('userCreate call callback')
})
}
}
如何将它们用作我的组件的方法?
我试过了,还是不行。嗯,我不确定我是否需要任何类(class)。
import React, { Component } from 'react'
import Register from './Register.jsx'
import FormFunctions from './FormFunctions'
class RegisterLogic extends Component {
render () {
return <Register
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
/>
}
}
export default RegisterLogic
最佳答案
您可以通过对代码进行两处小改动来实现此目的:
您将不得不使用
FormFunctions.handleChange
而不是 this.handleChange。为了能够从类中引用函数,您可以在其定义中添加静态:static handleChange (event) {
或创建和使用类的对象。无论出于何种原因,您调用
.bind(this)
来告诉 React 组件要使用哪个函数,因此您的代码变为handleChange={FormFunctions.handleChange。绑定(bind)(这个)}
。
希望这对您有所帮助。
关于javascript - React 使用外部函数作为方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375588/