【问题标题】:ReactJs : data from child to parent componentReactJs:从子组件到父组件的数据
【发布时间】:2017-10-01 22:55:53
【问题描述】:

我开始学习 React,但我很难找出这个错误。 我有一个父组件 Weather 和一个子组件 WeatherForm。从父组件中,我为子组件设置了一个属性。子组件是一个表单,目标是从输入中获取文本,当用户单击提交按钮时,输入文本被传递给父组件的函数,该函数显示带有文本的警报。

这是父组件:

const WeatherForm = require('WeatherForm');
const WeatherMessage = require('WeatherMessage');

class Weather extends Component {
constructor(props) {
    super(props);
    this.state = {
        location: ''
    };
    this.handleSearch = this.handleSearch.bind(this);
}
render() {
    return (
        <div>
            <h3>Weather component</h3>
            <WeatherForm onSearch={this.handleSearch} />
            <WeatherMessage />
        </div >
    );
}

handleSearch(value) {
    alert(value);
}


}

这是子组件:

class WeatherForm extends Component {
constructor(props) {
    super(props);
    this.onFormSubmit = this.onFormSubmit.bind(this);
}
render() {
    return (
        <div>
            <form onSubmit={this.onFormSubmit}>
                <input type="text" placeholder="Enter a city name" ref="location" onChange={this.onFormSubmit}/>
                <button>Get weather</button>
            </form>
        </div>
    );
}
onFormSubmit(e) {
    e.preventDefault();
    let location = this.refs.location;

    if (location.value && location.value.length > 0) {
        this.refs.location.value = '';
        props.onSearch(location.value);
    }

}
}

但是当我点击提交按钮时,我收到了这个错误:

props.onSearch 不是函数

我哪里出错了?

我还在另一个组件中的路由中使用父组件 Weather,例如 &lt;Route exact path="/" component={Weather} /&gt;

谢谢大家

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您的函数调用缺少 this 上下文。

    props.onSearch 更改为this.props.onSearch

    反映在您的处理程序中

    onFormSubmit(e) {
        e.preventDefault();
        const value = this.refs.location.value;
    
        if (value && value.length > 0) {
            this.refs.location.value = '';
            this.props.onSearch(value);
        }
    
    }
    

    【讨论】:

    • 谢谢你。你让我也意识到我使用的是大写 O 的 OnSearch 而不是真名 onSearch
    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 2016-03-18
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2018-07-17
    相关资源
    最近更新 更多