2017-05-03 66 views
1

我開始學習React,但我有一些困難找出這個錯誤。 我有一個父組件天氣和一個子組件WeatherForm。從父組件爲子組件設置一個屬性。子組件是一個表單,目標是從輸入中獲取文本,當用戶單擊提交按鈕時,輸入文本被傳遞給父組件的一個函數,該文件顯示一個警報。ReactJs:從子組件到父組件的數據

這是父組件:

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 is not a function

我在哪裏犯錯?

我也使用了父組件天氣在路由中的另一個組件這樣<Route exact path="/" component={Weather} />

感謝所有

回答

0

你缺少這種情況下你的函數調用。

變化props.onSearchthis.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); 
    } 

} 
+0

感謝你的傢伙。你讓我也意識到,我正在使用** OnSearch **與大寫O而不是真正的名字** onSearch **。 – Alee

相關問題