這裏是我的解決方案:
首先,定義在類的構造函數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>
);
}
}
希望這有助於!
Afaik,你不能通過驗證器來做到這一點。 相反,您處理表單提交時的檢查。 –
人,這是一個恥辱。我覺得實時驗證這將是一個更好的用戶體驗。 – miphe
那麼,你可以隨時寫它:) onTextChange =>堅持文本;驗證(); –