反应挂钩:父函数如何访问子函数的状态:如果单击按钮,父应用将读取子函数的状态

时间:2019-09-30 10:03:37

标签: javascript reactjs react-hooks

我正在努力“提升状态”以构建可折叠的组件。

我创建了两个功能:Button(子级)和App(父级)。如果用户单击按钮,它将[clicked]状态发送到应用程序(父)功能。

我希望App(父级)函数以某种方式访问​​子状态,并将其用作父函数内部的常量。

Button.js

import React, { useState } from "react";
import "./Button.css";

function Button() {
  const [clicked, setClicked] = useState(false);
  return (
    <div className="Button" onClick={() => setClicked(!clicked)}>
      <div>Click me!</div>
    </div>
  );
}
export default Button;

App.js

import React, { useState } from "react";
import logo from "./logo.svg";
import Button from "./components/Button";
import "./App.css";

function App() {
  /* const stateFromButton = ??? */
  return (
    <div className="App">
    /*Somehow from button component, passes its clicked state*/
      <Button />
      </div>
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

1 个答案:

答案 0 :(得分:0)

我们所做的: 1)将setState从父级传递给子级作为道具 2)在子onClick事件中,通过props调用该函数

这将是您的App.js

import React, {useState} from 'react';
import logo from './logo.svg';
import './App.css';
import './button.js';
import Button from "./button";

function App() {

    const [clicked, setState] = useState("TEST");

    return (
        <div className="App">
            <header className="App-header">
                <Button changeVal={() => setState("GOING TO PARENT")}>CLICK ME</Button>
                <img src={logo} className="App-logo" alt="logo"/>
                <p>
                    Edit <code>src/App.js</code> and save to reload.
                </p>
                <a
                    className="App-link"
                    href="https://reactjs.org"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    Learn React
                </a>
                <div>Value is {clicked}</div>
            </header>

        </div>
    );
}

export default App;

这将是Button.js

import React, {useState} from "react";

function Button(props) {
    return (
        <div className="Button"
             onClick={()=>props.changeVal()}>
            Click Me!
        </div>
    );
}

export default Button;