Set State不会更改React Native Slider上的值

问题描述 投票:0回答:1

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

 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

javascript react-native react-native-android arrow-functions
1个回答
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>
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.