reactjs - context api - 在上下文数据中循环
问题描述
我有一个代码,我每次使用上下文 API 从父组件向子组件传递一个名称,但我不知道如何循环从提供程序获取的上下文和多个
我把循环放在哪里?以及我如何将 JSX 用于多个
import React, { Component } from 'react';
import GrandChildComp_3 from './Demo3_GrandechildComp';
import myContext from './AppContext';
class ChildComp_3 extends Component {
constructor() {
super();
}
render() {
return (
<myContext.Consumer>
{(context) => (
<div className="App">
<h2>Child_3 comp</h2>
Name :{' '}
<ul>
<li>{context.name}</li>
</ul>
<GrandChildComp_3 />
</div>
)}
</myContext.Consumer>
);
}
}
export default ChildComp_3;
这是提供者的代码
import React, { Component } from 'react';
import ChildComp_3 from './Demo3_childComp';
import myContext from './AppContext';
class ParentsComp_3 extends Component {
constructor() {
super();
this.state = { name: [], age: [], name_arr: '', age_arr: '' };
}
getName = (e) => {
this.setState({ name_arr: e.target.value });
};
getAge = (e) => {
this.setState({ age_arr: e.target.value });
};
click = () => {
//name
let Name = this.state.name;
let N = this.state.name_arr;
Name.push(N);
this.setState({ name: Name });
//age
let Age = this.state.age;
let A = this.state.age_arr;
Age.push(A);
this.setState({ age: Age });
};
render() {
return (
<myContext.Provider value={{ name: this.state.name, age: this.state.age }}>
<div className="App">
<h2>ParentsComp_3 comp</h2>
Name : <input type="text" onChange={this.getName}></input>
<br />
Age: <input type="text" onChange={this.getAge}></input>
<br />
<input type="button" value="add" onClick={this.click}></input>
<ChildComp_3 name={this.state.name} />
</div>
</myContext.Provider>
);
}
}
export default ParentsComp_3;
解决方案
您需要映射名称数组以显示它们。
...
<ul>
{
name.map(n => <li>Name: {n}</li>
}
</ul>
另一方面,由于您将这些值传递给子组件,因此您不需要使用 Context API。您可以像在此处所做的那样直接将它们作为道具传递给子组件,但您没有在 ChildComp_3 中使用道具。
<ChildComp_3 name={this.state.name} />
推荐阅读
- parameters - ARIMA ACF 和 PACF
- java - 多个正则表达式模式来替换多次出现的图像标签
- c# - 如何在 EF Core Select 语句中将格式化日期字符串转换为大写
- python - 日期作为参数传递给 SQL Server 存储过程 - 从 pyodbc 脚本调用
- shell - 如何使用 sed 提取模式之间的线
- reactjs - Redux 提供程序未在加载时为 React 组件提供道具
- python - jinja,烧瓶中的for循环
- twilio - Twilio SMS (Whatsapp):发送位置
- xml - 无法在 wordpress 网站上验证 RSS 提要
- memory - Vulkan,我是否需要以及何时从 VK_* 结构中释放内存