2017-07-08 88 views
0

我嘗試爲滑塊創建一個重置按鈕,該按鈕會在按下時將其重置爲初始值。我的代碼不顯示任何錯誤,但重置按鈕不起作用。重置爲默認滑塊值react-native

這是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

這裏是有問題的一塊伸出馬上:

<ButtonReset resetSliderValue = {this.state.resetSliderValue}/>

我相信它應該是:

<ButtonReset resetSliderValue = {this.resetSliderValue}/>

而且,我相信你需要綁定this這樣你就可以在resetSliderValue功能設置狀態訪問this。我個人喜歡在構造函數中綁定一次函數,因此在渲染過程中不需要重新綁定:

constructor(props) { 
    super(props); 
    this.resetSliderValue = this.resetSliderValue.bind(this); 
} 
+0

我認爲'this'綁定將不是必需的,因爲他已經使用了ES7語法。 –

+0

謝謝你的回答完美。我還有另外一個問題:是否可以通過一個道具成爲一個孩子的狀態。例如:在子組件上,我定義了state = {this.props.example} –

+0

我不確定我理解你的問題。你可以將狀態值初始化爲道具。如果道具改變了,它就不會更新狀態,除非你監視它並處理'componentWillReceiveProps'生命週期方法中的更新。 –