我的视图看起来像这样(但为简单起见,我将其缩小了)
view.jsx
import * as R from 'ramda';
import { Validate } from 'src/utils/validate';
class example extends Component {
constructor(props) {
super(props);
this.state = {
model: EMPTY_MODEL,
validation: EMPTY_VALIDATION,
};
this.validate = R.bind(Validate, this);
}
render() {
<div>
<input
id="example"
type="text"
onChange={ this.validate }
/>
</div>
}
}
validate.js
import * as R from 'ramda';
export const Validate = ({ currentTarget }) => {
console.log(this); // outputs: {}
console.log(this.state); //outputs: undefined
debugger; //console.log(this.state); outputs { model: {}, validation: {} }
let { validation } = this.state; //Error: Cannot read prop 'validation'of undefined
const { id, value } = currentTarget;
switch (currentTarget.id) {
case 'example':
if(value.length < 4) {
this.setState({
validation: R.assocPath([id, 'valid'], false, validation),
});
}
break;
default:
break;
}
}
核心问题
this.state.validation
? (我想避免通过this
来验证为参数)需要理解的问题
undefined
,但是如果我在调试器中输出变量,则会得到期望的值?答案 0 :(得分:0)
就像skyboyer
一样,问题在于绑定箭头功能
validate.js中的内容已更改
export const Validate = ({ currentTarget }) => {
到
export const Validate = function ({ currentTarget }) {
答案 1 :(得分:-1)
您可以改用this.validate = Validate.bind(this);
吗?