我问了这个问题,如何将React的函数暴露给外部HTML: Use React in CMS and expose functions to HTML to access useState functions in React 因为找不到适合此功能的纯函数解决方案,所以我在类中进行了尝试,因为在类中存在可以绑定到窗口的“ this”。
import React from 'react';
import MyContext from '../context/Context';
class Api extends React.Component{
static contexType = MyContext;
constructor(){
super();
window.api = this;
}
exposed(value){
let c = this.context;
console.log("value", value)
console.log(c.number);
//c.setNumber({...number, "n1": value})
}
render(){
return(null);
}
}
export default Api;
在CMS模板中,我定义了此输入字段:
<input type="number" onchange="window.api.exposed(this.value)" />
onchange工作并调用暴露的()并给我实际值。但是,c.number始终是未定义的,并且c是一个空对象。
上下文在定义为Context.js的功能组件中正常工作
import React from 'react';
export default React.createContext({});
将Api组件插入到App.js中,如下所示:
function App() {
return (
<ContextProvider>
<Api />
</ContextProvider>
);
}
上下文提供者具有数字状态变量:
const [number, setNumber] = useState({"n1": 0, "n2": 1});
并将其放在上下文中:
return(
<MyContext.Provider value={{
number
}}>
<div className="contextProvider">
{props.children}
</div>
</MyContextContext.Provider>
);
为什么不能从类组件访问上下文?
答案 0 :(得分:1)
static contexType = MyContext;
缺少“ t”
static contextType = MyContext;