【发布时间】: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;
【问题讨论】: