首页 > 解决方案 > 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;
    
  • 标签: reactjsreact-context

    解决方案


    您需要映射名称数组以显示它们。

    ...
    <ul>
      {
         name.map(n => <li>Name: {n}</li>
      }
    </ul>
    

    另一方面,由于您将这些值传递给子组件,因此您不需要使用 Context API。您可以像在此处所做的那样直接将它们作为道具传递给子组件,但您没有在 ChildComp_3 中使用道具。

    <ChildComp_3 name={this.state.name} />
    

    推荐阅读