Set State不会更改React Native Slider

时间:2017-12-17 00:39:59

标签: javascript react-native react-native-android arrow-functions

所以我一直试图弄清楚如何在屏幕上更改文本组件的值。不幸的是,无论我做什么,价值都是一样的。 该值打印在终端上,但似乎不会更改屏幕上的文本。任何人都可以指出我正确的方向。任何帮助将不胜感激。

 const Speed =({navigation}) =>{

        // Set the Default State
        this.state = { age: 18 }

        getVal = (val) => {
          console.warn(val);
         }
        onChange = (v) => {

          this.setState({val:Math.round(v)});
          console.log(this.state );
        }

        return(
          <View >
          <Slider
               minimumValue = {0}
               maximumValue = {50} 
               value={this.state.age}
               onValueChange={val => this.setState({ age: val })}
               onSlidingComplete={ val => this.getVal(val)}

            />
            <Text>  {this.state.age}</Text>

            <Button 
              style = {{margin:50,backgroundColor:'black'}}
              title="Slow"
            />
            <Button 
              style = {{margin:50,backgroundColor:'black'}}
              title="Medium"
            />
            <Button 
              style = {{margin:50,backgroundColor:'black'}}
              title="Fast"
            />
          </View>
          );
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

你的Speed组件是stateless函数,尝试通过扩展Component类来重写它。

class Speed extends Component {
    constructor() {
        super();
        this.state = { age: 18 }
        this.getVal = this.getVal.bind(this);
        this.onChange = this.onChange.bind(this);
    }
        // Set the Default State

    getVal(val) {
        console.warn(val);
    }
    onChange(v) {
        this.setState({ val: Math.round(v) });
        console.log(this.state);
    }
    render() {
        return (
            <View >
                <Slider
                    minimumValue={0}
                    maximumValue={50}
                    value={this.state.age}
                    onValueChange={val => this.setState({ age: val })}
                    onSlidingComplete={val => this.getVal(val)}

                />
                <Text>  {this.state.age}</Text>

                <Button
                    style={{ margin: 50, backgroundColor: 'black' }}
                    title="Slow"
                />
                <Button
                    style={{ margin: 50, backgroundColor: 'black' }}
                    title="Medium"
                />
                <Button
                    style={{ margin: 50, backgroundColor: 'black' }}
                    title="Fast"
                />
            </View>
        );
    }
}