React Native 无法更新子组件中的状态

mspsb9vt  于 2023-01-31  发布在  React
关注(0)|答案(1)|浏览(225)

我想更改子组件中的状态值,但总是出现"this. setState不是函数"错误
父组件
'

export default class Todo extends Component {
   constructor(props){
    super(props)
    this.state = { 
      propBottomMenu : false
    }
    this.bottomRef = React.createRef()
  };
  checkClose(){
    this.setState({propBottomMenu : false})
  }
  render() {
    return (
      <>
     // other codes 
     <TouchableOpacity 
         onPress={() => this.setState({propBottomMenu : false})}
         style={styles.addTask}
          >
            <FontAwesomeIcon icon={ faPlus } size={25}  color={'#fff'} />
     </TouchableOpacity>
      {this.state.propBottomMenu ? 
         <BottomMenu bSheetRef={this.bottomRef} checkClose={this.checkClose} style=                       {styles.bottomMenu} /> 
        : null}
      </> 
    )
  }
}

'
子组件:
'

export default class BottomMenu extends Component {
    constructor(props){
        super(props)
        this.bottomRef = this.props.bSheetRef
     }
     render() {
       return (
     <>
        <BottomSheet 
            ref={this.bottomRef} 
            snapPoints={[ '40%', '60%', '90%']} 
            index={1}
            enablePanDownToClose={true}
            onChange={(index)=>{ index < 0 && this.props.checkClose() }}
           >
            // other codes 
          </BottomSheet>
        </>
      )
     }
   }
  })

'
checkClose()函数工作,但无法更新状态
错误:此. setState不是函数

zd287kbt

zd287kbt1#

解决方案:为了使函数工作,我们必须使用bind或将其作为arrow函数调用

constructor(props){
super(props)
this.checkClose = this.checkClose.bind(this); // this line 
this.state = { 
  propBottomMenu : false
}
this.bottomRef = React.createRef()
};

日本:

<BottomMenu bSheetRef={this.bottomRef} checkClose={this.checkClose} style={styles.bottomMenu} />

相关问题