我有一组组件,其中一个是search
组件,目前具有自己的状态。搜索时,它将使用匹配项的ID
更新其自身的状态。最终,我成为搜索组件,用于在Body
组件的状态下更新更多项目。但是,现在有一个好处。
我目前在Provider
中使用Body
,在Consumer
和Title
中使用Summary
。我在确切地了解如何操作时遇到了问题:
A:构建Body
组件的结构,这样我就可以拥有状态并保留已声明供提供程序使用的常量(如果需要保留它们的话)。
B:为Search
创建一个回调函数,以调用和更新Body
状态。
└── src/
└── COMPONENTS/
├── Body.js
│
├── SEARCH/
│ └── Search.js
│
└── WIKIHEADER/
├── WikiHeader.js
│
└── COMPONENTS/
├── Summary.js
└── Title.js
import React, {useState} from "react";
import WikiHeader from './wikiheader/WikiHeader'
import WikiReference from './wikireference/WikiReference'
import Search from './search/Search'
import GoogleAd from './googlead/GoogleAd'
import {SummaryContext} from "../contexts/SummaryContext"
import {ReferenceContext} from "../contexts/ReferenceContext"
function Body() {
const [wikiHeader, setWikiHeader] = useState('Hello from context');
const [wikiReference, setWikiReference] = useState('Hello from context');
return (
<>
<SummaryContext.Provider value={{wikiHeader, setWikiHeader}}>
<Search />
<WikiHeader />
<GoogleAd />
</SummaryContext.Provider>
<ReferenceContext.Provider value={{wikiReference, setWikiReference}}>
<WikiReference />
</ReferenceContext.Provider>
</>
);
}
export default Body;
import React, {Component} from "react";
import "../../App.css"
class Search extends Component {
state = {
searchCriteria: '',
resultId:0
}
handleSubmit = async (event) => {
event.preventDefault();
//fetch('http://127.0.0.1:5002/events/search/'+this.state.searchCriteria)
fetch('https://gist.githubusercontent.com/TheMightyLlama/e0ab261b30b7c957930b8eac29813180/raw/f39ea1323762b9dd796db7370a73f1a727e12566/gistfile2.txt')
.then(res => res.json())
.then((resultsData) => {
this.setState({
resultId: resultsData
})
console.log(resultsData);
})
.catch(console.log)
};
render() {
return (
<div className="search container">
<div className="input-group input-group-sm mb-3">
<div className="input-group-prepend">
<span className="input-group-text" id="inputGroup-sizing-sm">Wikipedia URL:</span>
</div>
<form onSubmit={this.handleSubmit}>
<input type="text" className="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" value={this.state.searchCriteria} onChange={event => this.setState({ searchCriteria: event.target.value })} placeholder="Search by event title" />
</form>
</div>
</div>
);
}
}
export default Search;
import React, {useContext} from "react"
import {SummaryContext} from "../../../contexts/SummaryContext"
import '../../../App.css'
export function Title() {
const {wikiHeader, setValue} = useContext(SummaryContext);
return (
<div className="container">
<div className="WikiPageTitle"><span><h3>{wikiHeader}</h3></span></div>
</div>
);
}