我有两个React组件,一个父组件和一个子组件。它们都在单独的文件中,代码如下所示:
import React, { Component } from 'react';
import SearchBar from './SearchBar';
import axios from "axios/index";
var processedQuery;
var url = 'https://some-url-api.com/q=';
class MainContent extends Component {
state = {
results: '',
query: ''
}
getData = () => {
axios.get(url + processedQuery)
.then(({ data }) => {
this.setState({
results: data
})
})
}
handleInputChange = () => {
processedQuery = this.search.value.split(' ').join('+');
this.setState({
query: processedQuery
}, () => {
this.getData();
}
)
}
render() {
return (
<div className="main-content">
<SearchBar handleInputChange={this.handleInputChange} />
</div>
);
}
}
export default MainContent;
以及子组件:
import React, { Component } from 'react';
class SearchBar extends Component {
render() {
return (
<div className="main-content__search-bar">
<form>
<input
type="text"
placeholder="Search for..."
onChange={this.props.handleInputChange}
/>
</form>
</div>
);
}
}
export default SearchBar;
当getData
和handleInputChange
函数位于子组件内部时,一切工作正常。但是,当我将它们移到父组件并尝试在输入中键入内容时,出现此错误:
Uncaught TypeError: Cannot read property 'value' of undefined
我多次遍历代码,但无法真正找到我所缺少的内容。有帮助吗?
答案 0 :(得分:3)
您的父组件应将新值用作参数:
handleInputChange = (event) => {
processedQuery = event.target.value.split(' ').join('+');
// ...
}
我认为孩子应该实际将值传递给(而不是事件)。
onChange={event => this.props.handleInputChange(event.target.value)}
父母可以这样做:
handleInputChange = (searchTerm) => {
processedQuery = searchTerm.split(' ').join('+');
// ...
}