reactjs - ReactJS - 从子组件调用父方法并等待父响应
问题描述
我刚开始使用 ReactJS,所以我还在掌握它的窍门。我需要一些我没有找到答案的方面的帮助。我正在尝试从子组件调用父组件中的函数,但我也想从父组件接收包含一些数据的答案。我怎样才能做到这一点?目前我正在做的是:
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click = () => {
this.props.parentMethod();
}
render() {
<div onClick={this.click}>Hello Child</div>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
}
}
解决方案
你通常不会这样做。数据从 React 中的 parent » child 流出。Parent
因此,如果对传递给 的更改数据执行函数Child
,您的Child
组件将重新渲染。
使用您的示例:
class Child extends React.Component {
render() {
<div onClick={this.props.changeName}>
Hello, {this.props.displayName}
</div>
}
}
class Parent extends React.Component {
constructor(){
this.state = {
name: "Bob",
}
}
changeName = () => {
this.setState({ name: "Sally" })
}
render() {
return(
<Child
changeName={this.changeName}
displayName={this.state.name}
/>
)
}
}
在这种情况下,单击div
内部Child
将更改's的name
属性,然后将其传递给并重新渲染。Parent
state
Child
推荐阅读
- css - 反应碳焦点铬的恼人边界
- javascript - 在 jqGrid 中选择新添加的行
- node.js - 使用 NodeJS 从 GCP 的存储中下载对象
- php - PHP将变量设置为json数据
- angularjs - MAT_DIALOG_DATA:错误:必须从注入上下文调用注入()错误:必须从注入上下文调用注入()
- java - Java Thymeleaf 如何替换文件
- outlook - Office 365 是否支持独立的 MAPI 调用
- php - 有什么办法可以两次包含相同的php文件?
- javascript - Google Maps GeoCode API 返回 NO_RESULTS 以按 PostalCode 进行搜索,但未指定地区/国家
- ios - 尝试使用 Firebase 动态链接,无法在 iOS 上打开应用