我是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
等,因此我的问题并非仅针对Switch
。 / p>
答案 0 :(得分:0)
在here的帮助下,我发现一种简单的方法是通过组成您的组件(在这种情况下为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风格,但这证明了这一概念。
答案 1 :(得分:0)
一种可能的解决方案(但我认为这不是最好的解决方案)将是在id
方法中初始化包含某种独特的componentDidMount
的值数组:< / p>
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 });
}
然后在渲染中:
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);
}