【问题标题】:context api - loop in context datacontext api - 在上下文数据中循环
【发布时间】: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


      【解决方案1】:

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

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

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

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

      【讨论】:

      • 我需要使用 Context api,因为我需要将数据传递给孙子
      • 但是您的回答非常有帮助,非常感谢!
      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      相关资源
      最近更新 更多