class function happend in every context at React.js code example
Example 1: defining functions in react
export default class Archive extends React.Component {
saySomething(something) {
console.log(something);
}
handleClick(e) {
this.saySomething("element clicked");
}
componentDidMount() {
this.saySomething("component did mount");
}
render() {
return <button onClick={this.handleClick.bind(this)} value="Click me" />;
}
}
Example 2: reactjs context
==App.js========================================
import React from 'react';
import PageContextProvider from './PageContextProvider';
import Header from './Header';
function App() {
return (
<div className="App">
<PageContextProvider>
<Header />
</PageContextProvider>
</div>
);
}
export default App;
==PageContextProvider.js=========================
import React, { useState, useEffect, createContext } from 'react';
export const PageContext = createContext();
const PageContextProvider = (props) => {
const [user, setUser] = useState({
'name': 'harry potter'
});
return (
<PageContext.Provider value={{
user: user,
}}>
{props.children}
</PageContext.Provider>
);
}
export default PageContextProvider;
==Header.js=====================================
import React, { useContext } from 'react';
import { PageContext } from './PageContextProvider';
const Header = () => {
const { user } = useContext(PageContext);
return (
<div className="header">
{user.name}
</div>
);
}
export default Header;