taro自定义组件

class Question extends Component{

  state={
    title:'',
    des:''
  }

  btnCancel(){
    //无法关闭自身,需要调用上层组建的方法(设置上层组件的属性)
    this.props.onCloseQuestion&&this.props.onCloseQuestion()
  }

  btnOk(){
    if (this.state.title&&this.state.des){
      this.props.onReceiveQuestion&&this.props.onReceiveQuestion(this.state)
    }
    else {
      Taro.showToast({title:'请输入标题和描述',icon:'none'})
    }
  }

  changeTitle(event){
    this.setState({
      title:event.target.value
    })
  }

  changeDes(event){
    this.setState({
      des:event.target.value
    })
  }

  render(){
    return(
      <Dialog>
        <View className='add-question'>
          <View className='question-body'>
            <Input focus onInput={this.changeTitle.bind(this)} className='ques-title' placeholder='输入问题标题'></Input>
            <Textarea onInput={this.changeDes.bind(this)} className='ques-des' placeholder='输入问题描述'></Textarea>
            <View className='btn-group'>
              <Button onClick={this.btnOk.bind(this)} className='btn-question ok'>确定</Button>
              <Button onClick={this.btnCancel.bind(this)} className='btn-question cancel'>取消 </Button>
            </View>
          </View>
        </View>
      </Dialog>
    )
  }
}

调用
onReceiveQuestion接收下层传入数据
onCloseQuestion 接收下层关闭事件(设置上层组件的属性)

{this.state.isShowDialog?<Question
          onReceiveQuestion={this.receiveQuestion.bind(this)}
          onCloseQuestion={this.closeQuestion.bind(this)}/>:null}

closeQuestion(){
//  关闭属性设置
    this.setState({
      isShowDialog:false
    })
  }

  receiveQuestion(options){
  //接收下层传入的属性,并设置
    let {questionList}=this.state
    questionList.push(options)
    this.setState({
      questionList:questionList
    },()=>{
      console.log(this.state.questionList)
      setStore('question',this.state.questionList)
    })
    
    this.closeQuestion()
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容