Reactjs 如何通过React上下文(从使用者到提供者)传递多个参数?
我正在使用CreateReact应用程序创建一个简单的应用程序 并且正在探索使用Reactjs 如何通过React上下文(从使用者到提供者)传递多个参数?,reactjs,create-react-app,Reactjs,Create React App,我正在使用CreateReact应用程序创建一个简单的应用程序 并且正在探索使用React-Context-API将少量内容从一个组件传递到另一个组件 Spice.js const spiceList = [ { id: 1, title: 'Spice 11', name: require('./images/spice1.jpeg') }, { id: 2, title: 'Spice 22', name: require('./i
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')
}
])
const SpiceContext=React.createContext(null)
导出默认上下文 首先创建要共享的对象
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>
{props.title}
{(选项)=>(
{options.map((option)=>(
))}
)}
在我的例子中,myOptions是一个对象数组。在这种情况下,请建议。如果您有一个列表要传递,我希望您会。映射此列表并呈现一个列表?
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>