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
的值,因此当您调用 setState 时,它会检查是否有任何更改,注意到它是相同的并且不会重新呈现零件。
您可以执行以下操作来重新渲染组件。这有点hacky 但它会起作用。通过将 RadioForm 上的键属性设置为状态中的值,并在您清除它时更新该值,它应该重新呈现表单。
代码如下:
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
})
}
}
关于react-native - 提交表单后清除单选按钮 react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276037/