Javascript 如何在material UI中实现上下文Api
我试图在组件中使用上下文API传递属性。我得到以下类型脚本错误 类型“String”上不存在属性“value” 我正在使用Javascript 如何在material UI中实现上下文Api,javascript,reactjs,typescript,frontend,material-ui,Javascript,Reactjs,Typescript,Frontend,Material Ui,我试图在组件中使用上下文API传递属性。我得到以下类型脚本错误 类型“String”上不存在属性“value” 我正在使用 export const TimeZoneContext = createContext("timeZone"); 然后在我的返回中为组件提供值 <TimeZoneContext.Provider value="timeZone" /> 我使用以下语句使用另一个组件的return语句中的值 <TimeZoneContext.Consumer>
export const TimeZoneContext = createContext("timeZone");
然后在我的返回中为组件提供值
<TimeZoneContext.Provider value="timeZone" />
我使用以下语句使用另一个组件的return语句中的值
<TimeZoneContext.Consumer>
{({ value }) => (
<TableCell className={classes.tableCell}>{value}</TableCell>
)}
</TimeZoneContext.Consumer>
{({value})=>(
{value}
)}
请随时询问更多需要的信息。谢谢实现嵌套上下文api与实现简单上下文api有何不同。我认为问题在于提供者和使用者中的组件没有共享关系。谢谢您可以使用useContext钩子来检索该值 这是你的代码修改 导出常量TimeZoneContext=createContext(“时区”); ReactDOM.render(, document.querySelector('#root'); //在App.js中,您应该看到值“PST” const context=useContext(TimeZoneContext); //可以在className的上下文中使用值 //在TableCell中使用值 {context}
您可以使用useContext钩子来检索值 这是你的代码修改 导出常量TimeZoneContext=createContext(“时区”); ReactDOM.render(, document.querySelector('#root'); //在App.js中,您应该看到值“PST” const context=useContext(TimeZoneContext); //可以在className的上下文中使用值 //在TableCell中使用值 {context}
希望能有所帮助@Garry我正在关注文档,但还没有任何帮助。我无法检索Consumer中的值。发布一个沙盒代码,模拟我当前在代码中所做的操作。希望能有帮助@Garry我正在关注文档,但还没有任何帮助。我无法检索Consumer中的值。发布一个沙盒代码,模拟我当前在代码中所做的操作。我应该提一下。提供者和使用者处于不同的组件结构中,未通过父级连接。所以导入应用程序将不起作用。我可能必须使用我应该提到的嵌套组件更新上下文。提供者和使用者处于不同的组件结构中,未通过父级连接。所以导入应用程序将不起作用。我可能必须使用嵌套组件更新上下文
export const TimeZoneContext = createContext("timeZone");
ReactDOM.render( <TimeZoneContext.Provider value="PST"><App/> </TimeZoneContext.Provider>,
document.querySelector('#root'));
//In your App.js you should see value 'PST'
const context = useContext(TimeZoneContext);
// You can use value in the context in className
<Table className={classes[context]}>
// Use value in TableCell
<TableCell>{context}</TableCell>