xml ui

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',
             '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',
         '100%',
        minHeight: '200px'
        }}
    >
        {'The theme here is ' + theme}
    </div>
}
render(Display)

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

原文地址:https://www.cnblogs.com/Searchor/p/13877931.html