简体   繁体   English

在 React 中通过 function 从父组件传递到子组件?

[英]Passing function via props from Parent to Child component in React?

I am having an issue where I'm trying to pass a function(updateEvents) via props from my App.js file to a NumberOfEvents.js file.我遇到一个问题,我试图通过道具将函数(updateEvents)从我的 App.js 文件传递到 NumberOfEvents.js 文件。 I passed the same function to another component with no issues.我将相同的 function 毫无问题地传递给了另一个组件。 However, when I try on the NumberOfEvents file, I get the following error: Error image Please help!!!但是,当我尝试 NumberOfEvents 文件时,出现以下错误:错误图像请帮助!!!

Here is the Parent:这是父母:

 import React, { Component } from 'react'; import EventList from './EventList'; import CitySearch from './CitySearch'; import NumberOfEvents from './NumberOfEvents'; import { extractLocations, getEvents } from './api'; import './nprogress.css'; import './App.css'; class App extends Component { state = { events: [], locations: [], numberOfEvents: 32 } componentDidMount() { this.mounted = true; getEvents().then((events) => { if (this.mounted) { this.setState({ events: events.slice(0, this.state.numberOfEvents), locations: extractLocations(events) }); } }); } componentWillUnmount() { this.mounted = false; } updateEvents = (location, eventCount) => { this.mounted = true; getEvents().then((events) => { const locationEvents = (location === 'all')? events: events.filter((event) => event.location === location); this.setState({ events: locationEvents, numberOfEvents: eventCount, }); }); }; render() { return ( <div className="App"> <CitySearch locations={this.state.locations} updateEvents={this.updateEvents} /> <EventList events={this.state.events} /> <NumberOfEvents numberOfEvents={this.state.numberOfEvents} updateEvents={this.updateEvents} /> </div> ); } } export default App;

And here is the Child:这是孩子:

 import React, { Component } from 'react'; class NumberOfEvents extends Component { state = { numberOfEvents: 32 } handleChange = (event) => { const value = event.target.value; this.setState({ numberOfEvents: value, }); this.props.updateEvents('', value); }; render() { return ( <input className="number" value={this.state.numberOfEvents} onChange={this.handleChange} /> ) } } export default NumberOfEvents;

try adding a constructor to the child component尝试向子组件添加构造函数

constructor(props) {
    super(props);
    this.state = {
        numberOfEvents: 32   
    }
}

Im not sure this will help...In Your Parent Component, inside return statement when passing the updateEvents Prop, try passing it as arrow function like this....我不确定这会有所帮助......在你的父组件中,在传递 updateEvents Prop 时在 return 语句内,尝试像这样将它作为箭头 function 传递......

updateEvents={ () => this.updateEvents() } />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM