这是我的解决方案:
首先,在类构造函数this.samePassword 中定义一个用于密码检查的类型。
this.samePassword = t.refinement(t.String, (s) => {
return s == this.state.person.user_password;
});
然后,在表单定义中使用this.samePassword 类型
this.Person = t.struct({
user_id: t.String,
user_password: t.String,
reenter_password: this.samePassword,
});
接下来,准备一个onChange 函数来处理文本更改并保存到状态。
this.validate 是一个变量,表示表单是否被输入。
onChange(person) {
this.setState({ person });
if(person.reenter_password != null && person.reenter_password != "") {
this.validate = this.refs.form.getValue();
}
}
最后,钩住this.state、this.onChange... 到<Form>
<Form
ref="form"
type={this.Person}
value={this.state.person}
onChange={(v) => this.onChange(v)}
options={this.options}
/>
完整代码如下:
import React from "react";
import {View, TouchableOpacity, Text} from "react-native";
import * as t from "tcomb-form-native";
let Form = t.form.Form;
export default class CreateUser extends React.Component {
constructor(props) {
super(props);
this.state = {
person: {}
};
this.samePassword = t.refinement(t.String, (s) => {
return s == this.state.person.user_password;
})
this.Person = t.struct({
user_id: t.String,
user_password: t.String,
reenter_password: this.samePassword,
});
this.options = {
fields: {
user_password: {
password: true,
secureTextEntry: true,
error: "",
},
reenter_password: {
password: true,
secureTextEntry: true,
error: "different password",
},
}
};
this.validate = null;
}
onChange(person) {
this.setState({ person });
if(person.reenter_password != null && person.reenter_password != "") {
this.validate = this.refs.form.getValue();
}
}
render() {
return (
<View>
<Form
ref="form"
type={this.Person}
value={this.state.person}
onChange={(v) => this.onChange(v)}
options={this.options}
/>
<View>
<TouchableOpacity
style={{backgroundColor: this.validate ? "blue": "red"}}
activeOpacity={this.validate ? 0.5 : 1}
disabled={this.validate? false: true}
onPress={() => this.doNext()}>
<Text> NEXT MOVE </Text>
</TouchableOpacity>
</View>
</View>
);
}
}
希望这会有所帮助!