我尝试为滑块创建一个重置按钮,按下时将其重置为初始值。我的代码没有显示任何错误,但重置按钮不起作用。
这是Slider组件:
import React, {Component} from 'react';
import {Slider,
Text,
StyleSheet,
View} from 'react-native';
import {ButtonReset} from './ResetButton.js'
export class SliderRoll extends Component {
state = {
value: 1,
};
resetSliderValue = () => this.setState({value : 1})
render() {
return (
<View style={styles.container}>
<Slider style={styles.slider}
minimumTrackTintColor={'blue'}
maximumTrackTintColor={'red'}
maximumValue = {2}
value= {this.state.value}
step={0.5}
onValueChange={(value) => this.setState({value: value})}
/>
<ButtonReset resetSliderValue = {this.state.resetSliderValue}/>
<Text style={styles.text} >
{this.state.value}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection:'column',
width: 150,
backgroundColor: 'pink',
marginLeft: 50,
justifyContent: 'center'
},
slider: {
width: 150,
},
text: {
fontSize: 20,
textAlign: 'center',
fontWeight: '500',
},
})
这是重置按钮:
import React, {Component} from 'react';
import {
Text,
View,
StyleSheet,
Image,
TouchableOpacity
} from 'react-native';
export class ButtonReset extends Component{
render(){
return(
<TouchableOpacity style = {styles.container}
onPress= {this.props.resetSliderValue}>
<Image
style={styles.button}
source={require('./restart.png')}
/>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
container: {
width: 50,
alignItems: 'center',
backgroundColor: 'pink',
marginLeft: 50,
marginTop: 10,
},
button: {
width:50,
height:50,
transform: [
{scale: 1}
]
}
})
答案 0 :(得分:0)
这是有问题的作品,立刻就出来了:
<ButtonReset resetSliderValue = {this.state.resetSliderValue}/>
我认为应该是:
<ButtonReset resetSliderValue = {this.resetSliderValue}/>
此外,我认为您需要绑定this
,以便您可以访问this
以设置resetSliderValue
功能中的状态。我个人喜欢在构造函数中为需要它的任何函数绑定一次,因此在渲染期间没有不必要的重新绑定:
constructor(props) {
super(props);
this.resetSliderValue = this.resetSliderValue.bind(this);
}