【问题标题】:How to pass multiple arguments through React Context (from Consumer to Provider)?如何通过 React Context 传递多个参数(从消费者到提供者)?
【发布时间】:2019-11-23 13:45:09
【问题描述】:

我正在使用 create-react-app 创建一个简单的应用程序

并且正在探索使用React Context API 将少量内容从一个组件传递到另一个组件。

Spice.js

const spiceList = [
  {
    id: 1,
    title: 'Spice 11',
    name: require('./images/spice1.jpeg')
  },
  {
    id: 2,
    title: 'Spice 22',
    name: require('./images/spice2.jpeg')
  }

];

return (
  <div>
    <h1>Welcome to Spices</h1>

 <SpiceContext.Provider value={'Masala'} imgSrc={img3}>
    <SpiceList/>
 </SpiceContext.Provider>
    </div>
  </div>
);

} }

导出默认 Spice;

SpiceList 中的消费者 我计划在其中检索多个属性而不是单个值属性。

如何做到这一点?谢谢

<>
                    <h1>{props.title}</h1>
                    <SpiceContext.Consumer>
                      {spiceContext=> <img src={spiceContext.value} alt={spiceContext.title}/>
                      }
                    </SpiceContext.Consumer>
      </>

SpiceContext

import React from 'react';

const SpiceContext = React.createContext(null);

导出默认 SpiceContext;

【问题讨论】:

    标签: reactjs create-react-app


    【解决方案1】:

    首先创建要共享的对象。

    const myOptions = [
      {
        key: 1,
        title: 'Title',
        other: 'other',
      },
      {
        key: 2,
        title: 'Title',
        other: 'other',
      }
    ];  
    

    然后传下去。

    return (
          <div>
            <h1>Welcome to Spices</h1>
    
         <SpiceContext.Provider value={myOptions} imgSrc={img3}>
            <SpiceList/>
         </SpiceContext.Provider>
            </div>
          </div>
        );
    

    那么你会以同样的方式收到:

    <h1>{props.title}</h1>
    <SpiceContext.Consumer>
      {(options) => (
        <>
          {options.map((option) => (
            <img key={option.key} src={option.other} alt={option.title}/>
          ))}
        </>
      )}
    </SpiceContext.Consumer>
    

    【讨论】:

    • 在我的例子中,myOptions 是一个对象数组。请在这种情况下提出建议。
    • 如果你有一个要传递的列表,我想你会 .map 这个列表并渲染一个 的列表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2011-06-04
    • 2020-09-29
    • 2020-02-06
    相关资源
    最近更新 更多