reactjs - 从子组件设置状态并使用 Context API 将其传递给父组件
问题描述
我有一个有状态的应用程序组件,它的任务是获取数据。它要获取的数据基于用户在输入字段中输入的内容。输入字段在另一个组件中,该组件被包装在组件中,而 App 组件被包装在组件中。
如何将输入字段中的数据传递到位于 Search.js 中的 onSearch 函数?应用程序.js
class App extends Component {
state = {
images: [],
value: '',
};
onSearch = (query) => {
axios
.get(
`https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${query}&per_page=24&format=json&nojsoncallback=1`
)
.then((res) => {
this.setState({
images: res.data.photos.photo,
});
})
.catch((err) => {
console.log('There was an error while trying to fetch the data: ', err);
});
};
render() {
return (
<Provider
value={{
images: this.state.images,
actions: {
onSearch: this.onSearch,
},
}}
>
<BrowserRouter>
<div className='container'>
<Header />
<PhotoList />
</div>
</BrowserRouter>
</Provider>
);
}
}
搜索.js
<Consumer>
{(context) => {
const handleChange = (e) => {
context.value(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
context.actions.onSearch();
e.currentTarget.reset();
};
return (
<form className='search-form' onSubmit={handleSubmit}>
<input
type='search'
name='search'
placeholder='Search'
required
/>
<button type='submit' className='search-button'>
<svg
fill='#fff'
height='24'
viewBox='0 0 23 23'
width='24'
xmlns='http://www.w3.org/2000/svg'
>
<path d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z' />
<path d='M0 0h24v24H0z' fill='none' />
</svg>
</button>
</form>
);
}}
</Consumer>
解决方案
推荐阅读
- excel - 如何使以下 iif 函数提供给定的结果?
- listview - Xamarin.Forms,仅限 iOS,作为 ViewCell 视图的框架的内容显示在列表中其他行的顶部
- javascript - 如何对antd表中的布尔列进行排序?
- linux - 在Linux中获取时钟设备的频率
- python - Python解析字符串值并加载到字典中
- reactjs - 必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks
- sql - SQL Server 2019 - 每天归档远程数据库,每个表中都有归档日期
- javascript - 我的功能会继续在购物车中添加产品,即使它存在并且没有显示任何警报。我该如何避免这个问题?
- sql-server - 不喜欢声明的问题
- java - 比较日期在java中没有按预期工作