登录.js
import FormValidation from './validation/Form' //this is Form.js
constructor(props) {
super(props);
this.state = {
submit: true,
errorMessage: ''
};
}
<span>{this.state.errorMessage}</span>
<label><input type="text" name="tel" onBlur={this.FormValidation.validation.phone.blur} value={this.state.telValue}/></label>
Form.js
let validation = {}
const FormValidation = (e) => {
validation = {
phone: {
blur: (e) => {
let v = e.target.value;
console.log(v);
if(v.length <= 0){
this.setState({submit: false, errorMessage: 'can not empty!'})
}
}
}
}
}
export default FormValidation;
首先我想将变量从input
传递给FormValidation
函数来验证这个输入,问题是:
TypeError: Cannot read property 'phone' of undefined
在线 onBlur={this.FormValidation.phone.blur}
第二个问题是我想从 Form.js
函数到 Login
组件setState
,如你所见,如果长度小于零应该使提交状态为 false
并设置 errorMessage
文本。
提前致谢
最佳答案
我已经为您的代码中有问题的部分添加了评论:
// FormValidation is a function, but in your input you are using it as an object.
const FormValidation = (e) => {
validation = {
phone: {
blur: (e) => {
let v = e.target.value;
console.log(v);
if (v.length <= 0) {
// FormValidation is not a React component, so it doesn't have a state. You should just return the error:
// return {submit: false, errorMessage: 'can not empty!'}
this.setState({submit: false, errorMessage: 'can not empty!'})
}
}
}
}
}
export default FormValidation;
这里是你可以做的:
登录.js
import FormValidation from './validation/Form' //this is Form.js
constructor(props) {
super(props);
this.state = {
submit: true,
errorMessage: '',
telValue: ''
};
handleBlur = (e) => {
const value = e.target.value
const validationError = FormValidation.validation.phone.blur(value)
if (validationError) {
this.setState({
submit: validationError.submit,
errorMessage: validationError.errorMessage
})
} else {
this.setState({
telValue: value
})
}
}
render () {
return (
<label>
<span>
{this.state.errorMessage}
</span>
<input type="text" name="tel" onBlur={this.handleBlur} value={this.state.telValue}/>
</label>
)
}
}
Form.js
let validation = {}
const FormValidation = {
validation = {
phone: {
blur: (value) => {
console.log(value);
if (value.length <= 0) {
return {submit: false, errorMessage: 'can not empty!'}
}
}
}
}
}
export default FormValidation;
关于javascript - ReactJs 将值传递给另一个 js 文件中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361239/