Javascript 在React中单击另一个组件中的按钮时触发另一个组件中的函数
当我在Javascript 在React中单击另一个组件中的按钮时触发另一个组件中的函数,javascript,reactjs,Javascript,Reactjs,当我在componentA 注意:两个组件都不是子组件的父组件 组件A import React from "react" function ComponentA(props) { return ( <div> <button>Start</button> </div> ) } export default ComponentA; 从“React”导入React 函数组
componentA
注意:两个组件都不是子组件的父组件
组件A
import React from "react"
function ComponentA(props) {
return (
<div>
<button>Start</button>
</div>
)
}
export default ComponentA;
从“React”导入React
函数组件a(props){
返回(
开始
)
}
导出默认组件a;
组件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;
从“React”导入React;
功能组件B(道具){
常量[isStarted,setStarted]=React.useState(false);
const start=()=>setStarted(true);
返回{isStarted?“开始…”:“未开始…”;
}
导出默认组件B;
一种方法是在ComponentA上创建一个回调道具,更改ComponentA父组件的状态,并通过道具将其传递给ComponentB,然后用useEffect捕捉道具更改
例如:
家长
函数父函数(){
常量[started,setStarted]=使用状态(false)
返回(
setStarted(true)}/>
)
}
组件a
import React from "react"
function ComponentA(props) {
return (
<div>
<button>Start</button>
</div>
)
}
export default ComponentA;
函数组件A({onClick}){
返回(
onClick()}/>
)
}
组件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;
函数组件B({started}){
常量[isStarted,setStarted]=React.useState(已启动);
useffect(()=>{
设置已启动(已启动)
},[开始])
返回{isStarted?“开始…”:“未开始…”;
}
另一种方法是使用useContext:
老实说,我有点懒得再举一个我认为更糟糕的例子。下面是一个使用useContext的示例,可能很有用。
使用Redux或类似的东西,即可观察到的东西上下文api呢?它们必须是某个东西的子对象,即使它只是一个窗口
start()
和关联的状态应该从两者的父级传递下来。请问如何使用useContext?我建议不要在应用程序中的任何地方使用useContext,尤其是当只有一个组件需要另一个组件的信息时(在您的情况下)。只有当多个组件需要相同的应用程序范围的数据时,才应该使用useContext。也就是说,你可以在这里找到文档:好的,你能用我上面的问题快速演示一下吗?编辑了我的答案