react-native-simple-radio-button
我有一个带有单选按钮的简单表单,我想在提交后清除表单,但没有清除,这很奇怪
这是代码:
import * as React from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import RadioForm, { RadioButton, RadioButtonInput, RadioButtonLabel } from 'react-native-simple-radio-button';
export default class App extends React.Component {
state = {
ages: [
{key:1,label:20},
{key:2,label:30},
{key:3,label:40},
],
initialRadioPos: -1
}
render() {
return (
<View style={styles.container}>
<View
style={{
flexDirection: 'column',
marginTop: 10,
alignItems: 'flex-start',
}}>
<RadioForm
radio_props={this.state.ages}
initial={this.state.initialRadioPos}
formHorizontal={false}
labelHorizontal={true}
buttonColor={this.state.switched ? '#673AB7' : '#A9A9A9'}
selectedButtonColor={this.state.switched ? '#673AB7' : '#A9A9A9'}
onPress={currentAge => {
this.setState({ currentAge });
}}
/>
<Button title="submit" onPress={()=>this.clear()}/>
</View>
</View>
);
}
clear = () =>{
this.setState({
initialRadioPos:-1
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
这是小吃上的代码,您可以查看它https://snack.expo.io/@andreh111/aW5zYW
我将按钮按下时将InitialRadioPos设置为-1,但是什么也没发生,但我认为代码逻辑是正确的...所以问题出在哪里
问题是您尚未更改initialRadioPos
so的值,因此当您调用setState时,它会检查是否有任何更改,请注意它是相同的,并且不会重新呈现该组件。
您可以执行以下操作重新渲染组件。这有点hacky,但可以使用。通过将RadioForm上的key属性设置为状态值,并在清除它时更新该值,它应该重新呈现该窗体。
这是代码:
import * as React from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import RadioForm, { RadioButton, RadioButtonInput, RadioButtonLabel } from 'react-native-simple-radio-button';
export default class App extends React.Component {
state = {
ages: [
{key:1,label:20},
{key:2,label:30},
{key:3,label:40},
],
initialRadioPos: -1,
formKey: 0 // set an initial key here
}
render() {
return (
<View style={styles.container}>
<View
style={{
flexDirection: 'column',
marginTop: 10,
alignItems: 'flex-start',
}}>
<RadioForm
key={this.state.formKey} // set the key prop to the value in state
radio_props={this.state.ages}
initial={this.state.initialRadioPos}
formHorizontal={false}
labelHorizontal={true}
buttonColor={this.state.switched ? '#673AB7' : '#A9A9A9'}
selectedButtonColor={this.state.switched ? '#673AB7' : '#A9A9A9'}
onPress={currentAge => {
this.setState({ currentAge });
}}
/>
<Button title="submit" onPress={()=>this.clear()}/>
</View>
</View>
);
}
clear = () =>{
this.setState({
formKey: Math.random() // update the key
})
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句