如何在React Native中将TextInput的值传递给MobX action?
实现方案:把TextInput值同步到MobX Store并提交弹出
没问题,我帮你梳理下具体实现步骤,核心是把输入框的实时值同步到MobX的TestStore,再让Store读取自身存储的值完成弹窗展示,下面是修改后的完整代码和说明:
1. 完善TestStore:添加同步输入值的Action并更新弹窗逻辑
MobX推荐用action方法修改可观察变量(observable),所以我们先给TestStore加一个专门更新email的方法,同时修改弹窗方法让它读取存储的email值:
import { observable, action } from "mobx"; export default class TestStore { @observable email = null; // 新增:同步输入框值到Store的action @action setEmail = (text) => { this.email = text; }; // 修改:弹窗展示Store中存储的email值 @action alert = () => { alert(`The value you entered is ${this.email || 'empty'}`); }; }
2. 修改Home.js:同步输入值到Store并保留原有校验逻辑
在TextInput的onChangeText回调里,既要执行你原本的校验逻辑,也要调用Store的setEmail方法同步输入值,确保视图和Store数据保持一致:
// Home.js中的TextInput和提交按钮部分 <TextInput style={[ !this.state.email ? { borderWidth: 3, borderColor: 'red' } : null]} onChangeText={(text) => { // 先执行你的原有校验逻辑(更新组件state做样式提示) this.validate(text, 'email'); // 同步输入值到MobX Store this.props.testStore.setEmail(text); }} value={this.state.email} maxLength={100} /> <TouchableOpacity style={ [{ width: '70%', backgroundColor: this.state.buttonInvalid ? '#607D8B' : '#009688' } ]} activeOpacity={.5} disabled={this.state.buttonInvalid} onPress={this.props.testStore.alert} > <Text>Submit</Text> </TouchableOpacity>
可选优化:让视图完全依赖Store数据
如果想简化代码,你可以去掉组件自身的email state,直接用Store的email值控制输入框的内容和校验样式,这样更符合MobX的单向数据流理念:
// 修改后的TextInput部分 <TextInput style={[ !this.props.testStore.email ? { borderWidth: 3, borderColor: 'red' } : null]} onChangeText={(text) => { this.props.testStore.setEmail(text); // 校验逻辑可以直接基于Store的值做,比如更新buttonInvalid状态 this.setState({ buttonInvalid: !text }); }} value={this.props.testStore.email} maxLength={100} />
内容的提问来源于stack exchange,提问作者Dino
相关产品推荐
相关产品推荐

