[英]React: How to get results from one component to another component
I am trying to create a search component, which should have an input field and a result list. 我正在尝试创建一个搜索组件,该组件应具有一个输入字段和一个结果列表。 My problem is how to get the result data to the result component. 我的问题是如何将结果数据发送到结果组件。
This is the input component: 这是输入组件:
import React, { Component } from 'react'
import { searchData } from '/imports/api/search/methods.js';
export default class Search extends Component {
handleChange(event) {
searchData.call(
{ value: event.target.value },
(error, result) => {
if (result && result.length > 0) {
console.log(result); // <-- Send this results to result component
}
}
);
}
render() {
return (
<input type="text"
onChange={this.handleChange}
placeholder='Search'
/>
)
}
}
And this should be my result list, which should be shown only if there is any result: 这应该是我的结果列表,仅在有任何结果时才显示:
import React, { Component } from 'react'
export default class SearchResult extends Component {
render() {
return (
<ul>
<li>
// Show all result elements
</li>
</ul>
)
}
}
You could create a parent component, containing both Search
and SearchResult
, that would hold some internal state. 您可以创建一个包含Search
和SearchResult
的父组件,该组件将保留一些内部状态。
That way when you get your results inside your handleChange
method, you can invoke a prop callback to pass the data up to parent, hence calling inside the parent this.setState()
with the data and then passing that data down to your SearchResults
with props. 这样,当您在handleChange
方法中获取结果时,可以调用prop回调以将数据传递给父对象,从而在父this.setState()
内部使用数据调用this.setState()
,然后使用props将数据向下传递给SearchResults
。
This technique is generally known as lifting the state up 此技术通常称为提升状态
An example of that container could be: 该容器的示例可能是:
class SearchContainer extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
this.handleResultChange = this.handleResultChange.bind(this);
}
handleResultChange(data) {
this.setState({
data,
});
}
render() {
return (
<div>
<Search onDataFetched={this.handleResultChange} />
<SearchResult data={this.state.data} />
</div>
)
}
}
Then, inside your Search component, replace console.log(result);
然后,在您的Search组件内,替换console.log(result);
with this.props.onDataFetched(result)
使用this.props.onDataFetched(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.