繁体   English   中英

在 React 中单击来自不同组件的按钮时触发另一个组件中的函数

[英]Trigger a function in another component on click a button from a different component in React

我试图触发启动功能在不同的componentB当我点击开始按钮componentA

注意:两个组件都不是子组件的父组件

组分 A

import React from "react"

function ComponentA(props) {        
  return (
    <div>
      <button>Start</button>
    </div>
  )
}

export default ComponentA; 

组分 B

import React from "react";

function ComponentB(props) {
  const [isStarted, setStarted] = React.useState(false);

  const start = () => setStarted(true);

  return <div>{isStarted ? "Starting..." : "Not Starting.."}</div>;
}

export default ComponentB;

一种方法是在 ComponentA 上创建一个回调 prop,更改 ComponentA 的父组件的状态并通过 prop 将其传递给 ComponentB,并使用 useEffect 捕获该 prop 更改。

例子:

家长

function Parent(){
  const [started, setStarted] = useState(false)

  return(
    <div>
      <ComponentA onClick={() => setStarted(true)}/>
      <ComponentB started={started}/>
    </div>
  )
}

组件A

function ComponentA({onClick}){
  return(
    <div>
      <button onClick={() => onClick()}/>
    </div>
  )
}

组件B

function ComponentB({started}) {
  const [isStarted, setStarted] = React.useState(started);

  useEffect(() => {
    setStarted(started)
  }, [started])

  return <div>{isStarted ? "Starting..." : "Not Starting.."}</div>;
}

另一种方法是使用 useContext:

https://reactjs.org/docs/hooks-reference.html#usecontext

https://reactjs.org/docs/context.html

老实说,我有点懒惰,还包括一个我认为更糟糕的例子。 这是一个使用可能有用的 useContext 的示例。 https://stackoverflow.com/a/54738889/7491597

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM