[英]How do i click a button in parent component and access the data in child component?
I am working with the concepts of ReactJS and stumbled upon this very interesting case,我正在研究 ReactJS 的概念并偶然发现了这个非常有趣的案例,
I have a button in my parent component, which when clicked will access a simple string defined in child component.我的父组件中有一个按钮,单击该按钮将访问子组件中定义的简单字符串。
I understand to pass data from parent to child we use, and to a child to parent we have to use callback functions, But I am not sure how do I use callback function in this scenario.我知道将数据从父级传递给我们使用的子级,将数据传递给父级的子级我们必须使用回调函数,但我不确定在这种情况下如何使用回调函数。 I have played around a little with defining function etc but nothing seems to really work.我在定义函数等方面玩了一些,但似乎没有任何效果。
My Main.js file我的 Main.js 文件
import React from "react";
import Child from "./Child";
function handleClick(props) {
console.log("clicked");
}
function Main(props) {
return (
<div>
<button onClick={handleClick}>click</button>
{console.log(props)}
</div>
);
}
export default Main;
My Child.js component我的 Child.js 组件
import React from "react";
function statement() {
return "A sentence";
}
function Child(props) {
// let sentence = "This is from the child component";
return (
<div>
<p>The child says {props.name} </p>
</div>
);
}
export default Child;
Thank you for reading, sorry if it sounds too basic.感谢您的阅读,如果这听起来太基础,请见谅。 Any help would be much appreciated.任何帮助将非常感激。
you can create a ref in parent component and pass it to child component and then access the child state through that ref like:您可以在父组件中创建一个 ref 并将其传递给子组件,然后通过该 ref 访问子状态,例如:
function Main(props) {
const child = useRef()
const handleClick = () => {
// get child state
child.current.getState()
}
return <Child innerRef={child} />
}
function Child({ innerRef }) {
const [someState, setSomeState] = useState()
useImperativeRef(innerRef, () => ({ getState: () => someState }), [someState])
return <SomeComponent />
}
You can read more about above code in official docs.您可以在官方文档中阅读有关上述代码的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.