【发布时间】:2021-03-01 16:41:17
【问题描述】:
我有一个代码,我每次使用上下文 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;
【问题讨论】:
标签: reactjs context-api