使用 React 16.8^ 编码风格从子组件获取状态变量

Get state variable from child component using React 16.8^ coding style

这个问题已经有人问过,但我无法使用 hooks 找到答案。

我需要在调用组件的页面中读取一个状态变量。

MyPage.js

import React from "react"
import MyComponent from "../components/MyComponent"

export default function MyPage() {
  console.log("Read stateVariable value here " + stateVariable) // produce error
  return (
      <MyComponent />
  )
}

MyComponent.js

import React, { useState } from "react"
import ExternalModule from "ExternalModule"

export default function MyComponent() {

const [stateVariable, setStateVariable] = useState(0))

 return (
    <div
      onClick={setStateVariable(stateVariable + 1)}
    >CLICK HERE
      <ExternalModule
        stateVariable={stateVariable}
      />
    </div>
  )

如何在我的页面中console.logstateVariable

当您有多个组件需要访问一个状态时,您希望该状态由树中的 highest-up 组件拥有并传递给其余组件。

useState 调用向上移动到 MyPage 并将 stateVariablesetStateVariable 作为属性向下传递到 MyComponent

export default function MyPage() {

    const [stateVariable, setStateVariable] = useState(0)

    console.log("Read stateVariable value here " + stateVariable)

    return (
        <MyComponent 
            stateVariable={stateVariable} 
            setStateVariable={setStateVariable} 
        />
    )
}

export default function MyComponent({ stateVariable, setStateVariable]) {
    return (
        <div
            onClick={setStateVariable(stateVariable + 1)}
        >CLICK HERE
            <ExternalModule
                stateVariable={stateVariable}
            />
        </div>
    )
}