![](/img/trans.png)
[英]how do i change the state of a component after a button is pressed using text input in react native?
[英]React Native - How do I know which dynamic Component was pressed?
我是React Native的新手,正在创建一个包含多个Switch的屏幕,直到运行时才知道其数量和详细信息。
在onValueChange
回调中,传入了Switch的新值,但是如何识别实际按下了哪个Switch? (代码简化)
export default class Class1 extends Component
{
switchhit(newval)
{
console.log('*How do I know which switch was hit?* newval=' + newval);
}
render()
{
let ii, arrC = [];
for (ii = 0; ii < sSettChcs.length; ii++)
{
let jsx0 =
<View>
<View>
<Text>{ sSettChcs[ii] }</Text>
<Text>{ sSettDesc[ii] }</Text>
</View>
<View>
<Switch
onValueChange = { (newval) => this.switchhit(newval) }
value = { true } />
</View>
</View>;
arrC.push(jsx0);
}
let jsx =
<ScrollView>{ arrC }</ScrollView>;
return jsx;
}
}
请注意,这是一个简化的示例,最终屏幕将具有类型为TextInput
, Picker
等的Components,所以我的问题并非仅针对Switch
。
在这里有一些帮助,我发现一种简单的方法是通过组成您的组件来“子类化”(在这种情况下为Switch
)并存储一个标识符(下面的idx0
):
class MySwitch extends Component
{
swbang(newval)
{
console.log('newval=' + newval + 'idx0=' + this.props.idx0);
}
render()
{
return (
<View>
<Switch
onValueChange = { (newval) => this.swbang(newval) }
value = { true } />
</View>
);
}
}
原始代码将变为:
export default class Class1 extends Component
{
render()
{
let ii, arrC = [];
for (ii = 0; ii < sSettChcs.length; ii++)
{
let jsx0 =
<View>
<View>
<Text>{ sSettChcs[ii] }</Text>
<Text>{ sSettDesc[ii] }</Text>
</View>
<View>
<MySwitch idx0 = { ii } />
</View>
</View>;
arrC.push(jsx0);
}
let jsx =
<ScrollView>{ arrC }</ScrollView>;
return jsx;
}
}
回想起来很简单,但是来自Java / C类型世界却并不直观。
我确信这可以做得更好,并且某些方面不符合React Native风格,但这证明了这一概念。
一个可能的解决方案(但我认为这不是最好的解决方案)将是初始化一个值数组,该数组在componentDidMount
方法中包含某种唯一的id
:
componentDidMount() {
const data = [];
// You'll probably need to set this sSettChcs array in the state
for (i = 0; i < sSettChcs.length; i++) {
data.push({ id: i, value: false });
}
this.setState({ data });
}
然后重写您的switchint
函数,如下所示:
switchhit(newval, id)
{
const newData = [];
this.state.data.forEach(val => {
if (val.id === id) {
newData.push({ id, value: newval });
} else {
newData.push(val);
}
});
this.setState({ data: newData });
}
然后,在render中:
for (ii = 0; ii < this.state.data.length; ii++)
{
let jsx0 =
<View>
<View>
<Text>{ sSettChcs[ii] }</Text>
<Text>{ sSettDesc[ii] }</Text>
</View>
<View>
<Switch
onValueChange = { (newval) => this.switchhit(newval, this.state.data[ii].id) }
value = { this.state.data[ii].value } />
</View>
</View>;
arrC.push(jsx0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.