xml ui - context

useContext saves you the stress of having to rely on a Context consumer.

const contextValue = useContext(contextObject)
// consuming context via a consumer: 
const ThemeContext = React.createContext("dark");

function Button() {
    return <ThemeContext.Consumer>
        {theme => <button className={theme}>Amazing button</button>}
    </ThemeContext.Consumer>
}
const ThemeContext = React.createContext('light')

const Display = () => {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <div
          style={{
            background: theme === 'dark' ? 'black' : 'papayawhip',
            color: theme === 'dark' ? 'white' : 'palevioletred',
            width: '100%',
            minHeight: '200px'
          }}
        >
          {'The theme here is ' + theme}
        </div>
      )}
    </ThemeContext.Consumer>
  )
}
render(Display)
// consume context with the useContext hook: 
import {useContext} from 'react';

function ButtonHooks() {
  const theme = useContext(ThemeContext)
  return <button className={theme}>Amazing button</button>
}
const ThemeContext = React.createContext('light');

const Display = () => {
 const theme = useContext(ThemeContext);
 return <div
        style={{
        background: theme === 'dark' ? 'black' : 'papayawhip',
        color: theme === 'dark' ? 'white' : 'palevioletred',
        width: '100%',
        minHeight: '200px'
        }}
    >
        {'The theme here is ' + theme}
    </div>
}
render(Display)

https://react-hooks-cheatsheet.com/

posted @ 2020-10-26 13:07  fndefbwefsowpvqfx  阅读(47)  评论(0编辑  收藏  举报