在按钮单击时从子组件向父组件发送值

时间:2018-02-07 04:58:40

标签: reactjs

我有一个react组件,它封装了两个子组件。其中一个子组件包含输入字段和按钮。单击该按钮,我想将输入字段的内容发送到父组件以进行进一步操作。

这是我到目前为止所做的:

父组件:

//WorldTimeDate.js
import React from "react";
import SearchWorldTimeDate from "./SearchWorldTimeDate.js";
import Style from "./WorldTimeDate.less";

export default class WorldTimeDate extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (
            <div className={Style.WorldTimeDate}>
                <SearchWorldTimeDate />
            </div>
        )
    }
}

子组件:

import React from "react";
import Style from "./SearchWorldTimeDate.less";

export default class SearchWorldTimeDate extends React.Component {

    constructor() {
        super();
        this.state = {
            inputValue: ""
        }
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    searchClick() {
        console.log(this.state.inputValue);
    }

    handleInputChange(event) {
        this.setState({inputValue: event.target.value});
    }

    render() {
        return (
            <div className={Style.SearchWorldTimeDate}>
                <input onChange={this.handleInputChange} />
                <button onClick={ () => this.searchClick()}>Go</button>
            </div>
        )
    }
}

您可以看到,到目前为止,我在更​​新搜索字段时更新了我的子组件的inputValue状态,并且在单击按钮时会触发searchClick函数。

我知道需要将此inputValue发送回父类。我怎么能这样做?

0 个答案:

没有答案
相关问题