首页 > 解决方案 > 在方法中反应更新状态并传递它

问题描述

我正在尝试更新方法 start() 中的状态,然后将状态的值传递给 MyComponent。我的组件工作正常,当我在类中设置它时状态更新正常,但是当我试图从 start 方法传递它时 - 它不起作用。得到“TypeError:this.setState 不是函数”

已编辑 - 固定绑定,但仍然无法正常工作。

可能是什么问题?

export default class App extends Component{
  constructor (props){
    super(props);
    this.state = {
      val: false
    }
    this.start= this.start.bind(this)

  }

  start() {
    this.setState({ val: true })
  }

  render(){
    return (
      <View>
        <Button 
        title='start' 
        onPress={this.start}>
        </Button>

        <MyComponent value={this.state.val}> </MyComponent>
      </View>
    );
  }
}

这是我的组件:

class MyComponent extends Component {
     constructor(props){
         super(props)
         this.state={}
         this.state.custum={
            backgroundColor: 'red'
         }
         let intervalid;
         if (this.props.value){
            setTimeout(() => {
                this.setState( {
                    custum:{
                        backgroundColor: 'green'
                    }
                    })
            }, 1000);
            setTimeout(() => {
                this.setState( {
                    custum:{
                        backgroundColor: 'red'
                    }
                    })
            }, 2000);
        }
     }    
    render() {
        return (
            <View style={[styles.old, this.state.custum]}> 
            </View>
        );
      }
    }  
    var styles = StyleSheet.create({
        old:{
          padding: 5,
          height: 80,
          width: 80,  
          borderRadius:160,    

        },
    })
export default MyComponent;

标签: javascriptreactjsreact-nativestate

解决方案


您必须将上下文绑定到您的函数。

 constructor (props){
      super(props);
        this.state = {
        val: false
    }
    this.start = this.start.bind(this)
  }

或者只是您可以使用箭头功能,无需绑定

 start = () => {
     this.setState({ val: true })
 }

推荐阅读