我正在做一个简单的测试,在父组件中有一个name状态,当单击子项中的按钮时,该状态会更新。但这是行不通的,如果我做错了事,我会感到困惑。

上级:

import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Hello test={handle} />
      {name}
    </div>
  );
}



儿童:

import React from "react";

export default function App() {
  return (
    <div>
      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>
    </div>
  );
}


我究竟做错了什么?

最佳答案

将功能作为道具传递。

import React from "react";

export default function App({ handle }) {
  return (
    <div>
      <button onClick={() => handle('TEST')}>Activate Lasers</button>
    </div>
  );
}


并像

<Hello handle={handle} />




// Get a hook function
const {useState} = React;

function Hello({ handle }) {
  return (
    <div>
      <button onClick={() => handle('TEST')}>Activate Lasers</button>
    </div>
  );
}

function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Hello handle={handle} />
      {name}
    </div>
  );
}


// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

10-07 21:58