React Native Picker下基于选中状态实现两个TextInput的条件渲染
代码调整方案
1. 先修复Picker的参数逻辑错误
你当前的<Picker.Item>配置存在核心逻辑偏差:选项的value属性传入的是实时价格数值,会导致selectedValue存储的是价格而非「Buy/Sell」的类别标识,后续所有匹配判断都会失效。需要把两个选项的value改成对应类别的固定字符串,价格字段可以在需要的时候根据选中的类别单独取值。
修正后的Picker代码:
<Picker mode="dropdown" selectedValue={selectedValue} style={{ height: 50, width: 150 }} onValueChange={(itemValue) => setSelectedValue(itemValue)} > {/* value直接存类别标识,价格需要时根据selectedValue取即可 */} <Picker.Item label="Buy" value="Buy" /> <Picker.Item label="Sell" value="Sell" /> </Picker>
如果后续需要用到对应价格,比如选中Buy时取currency.data.prices[clickedindex].closeoutAsk,选中Sell时取closeoutBid,直接写判断取值即可,不用把价格塞进Picker的value属性里。
2. 给TextInput加条件渲染逻辑
利用JSX的短路判断实现互斥渲染:只有选中对应选项时,才渲染绑定对应阈值的输入框,两个输入框不会同时出现。
另外补充兼容调整:React Native的TextInput组件要求绑定的value是字符串类型,你原来的阈值状态初始值是数字0,会触发类型警告,建议把初始值改成空字符串。
调整后的状态声明:
// 原状态修正,初始值改为空字符串适配TextInput类型要求 const [BuyThreshhold, setBuyThreshhold] = useState('') const [SellThreshhold, setSellThreshhold] = useState('')
调整后的输入框渲染逻辑:
{/* 选中Buy时才渲染Buy阈值输入框 */} {selectedValue === 'Buy' && ( <TextInput style={{backgroundColor: "lightgrey", borderRadius: 5, width: 100, height: 50, textAlign: "center"}} value={BuyThreshhold} onChangeText={(text) => setBuyThreshhold(text)} placeholder="BuyThreshold" keyboardType="decimal-pad" placeholderTextColor="#60605e" /> )} {/* 选中Sell时才渲染Sell阈值输入框 */} {selectedValue === 'Sell' && ( <TextInput style={{backgroundColor: "lightgrey", borderRadius: 5, width: 100, height: 50, textAlign: "center"}} value={SellThreshhold} onChangeText={(text) => setSellThreshhold(text)} placeholder="SellThreshold" keyboardType="decimal-pad" placeholderTextColor="#60605e" /> )}
实际效果
- 初始状态
selectedValue默认是"Buy",页面加载时自动显示Buy的阈值输入框 - 切换Picker选项到Sell时,Buy的输入框会自动卸载,替换成Sell的阈值输入框,两者不会同时显示
- 两个阈值的状态独立存储,切换选项时不会丢失之前输入的数值
内容的提问来源于stack exchange,提问作者user23424
相关产品推荐
相关产品推荐

