【问题标题】:how to pass the result from one component to another with reactjs hooks?如何使用 reactjs 挂钩将结果从一个组件传递到另一个组件?
【发布时间】:2021-09-02 18:44:01
【问题描述】:

我有两个组件:第一个有一个计数按钮,第二个会显示结果

import React, { useState } from 'react';

function Count() {

  const [count, setCount] = useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}


现在我需要在另一个组件中显示结果:

import React, { useState } from 'react';

import Count from './Count'

function Result() {

  return <p>You clicked {count} times</p>;

}

还是不行,怎么解决?

【问题讨论】:

  • 这是对组件是什么以及如何使用它们的根本误解。您可以考虑阅读一些 React 教程以更好地理解基础知识。

标签: javascript reactjs react-hooks


【解决方案1】:

react 钩子不会在组件之间共享状态。但是您解释的结构可以通过多种方式轻松实现。要在不使用外部库的情况下实现它,您可以使用反应上下文 API

const NumberContext = React.createContext();

  const [count, setCount] = useState(0);
  <Counter.Provider value={[count, setCount]}>
    <Count />
    <Result />
  </Counter.Provider>,

并在你的组件中而不是 useState 使用

const [count, setCount] = useContext(NumberContext);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2018-03-07
    • 2019-12-02
    • 2022-11-01
    • 2020-12-30
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多