簡體   English   中英

反應如何將方法發送到 childComponent

[英]React how to send method to childComponent

嗨,我無法在反應中將方法從父級發送到子級。 我以前做過這個,它有效......為什么它不再有效了?

我正在渲染這個:

<div>
     <ScheduleSelectModal colupdate={this.updateColumn.bind(this)} subject={this.state.selectedSubject} subjectslist={this.state.mySubjects} show={this.state.modalShow} onHide={this.changeModalState.bind(this)}>
                </ScheduleSelectModal>
            </div>

這是我的方法:


    updateColumn(newSubject,dayId){
        console.log("tu som");
        console.log(this.state.schedule);
    }

我的模態:

 ScheduleSelectModal extends Component {

   componentDidUpdate(prevProps, prevState, snapshot) {
       console.log("modal props:");
       console.log(this.props.subject);
   }

   update(){
       console.log("updating...");
       this.props.updatecolumn("test","test");
   }

    createList() {
        let items = [];
        if (this.props.subjectslist !== null)
            this.props.subjectslist.map(subject =>
                items.push(<Button key={subject.id} block className={"my-1"} onClick={this.update.bind(this)}>{subject.name} </Button>)
            );

        return items;
    }


    render() {
        return (
            <Modal
                {...this.props}
                size="lg"
                aria-labelledby="contained-modal-title-vcenter"
                centered
            >
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-vcenter">
                        {this.renderHeader()}
                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <ButtonGroup vertical className={"w-100"}>
                        {this.createList()}
                    </ButtonGroup>
                </Modal.Body>
            </Modal>
        );
    }
}

這是我收到的警告:

index.js:1375 Warning: Invalid value for prop `colupdate` on <div> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.

真的不知道是什么問題。 謝謝幫助

class ParentComponent extends Component {
    passedFunction = () => {}
    render() {
      <ChildComponent passedFunction={this.passedFunction}/>
    }
}


class ChildComponent extends Component {
    render() {
        <div onClick={this.props.passedFunction}></div>
    }
}

您可以使用箭頭函數來避免所有綁定。 如果你想綁定它,像這樣在構造函數中綁定它......在父組件中。

constructor() {
        this.passedFunction = this.passedFunction.bind(this)
    }

<ChildComponent passedFunction={this.passedFunction}/>

我可以看到,在您使用的子組件中:

update(){
       console.log("updating...");
       this.props.updatecolumn("test","test");
   }

但是您對該功能的道具是 colupdate ,即您應該使用

update(){
           console.log("updating...");
          this.porps.colupdate("test","test");
       }

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM