我想从类函数外部获取子组件文件
函数saveSurveyData(survey)需要调用父函数handleTabs()
class Parent extends React.Component {
constructor(props){
super(props);
this.handleTabs = this.handleTabs.bind(this);
}
handleTabs = () => {
console.log('expecting call from Child component - function
}
render() {
return (
<Tab eventKey={1} title="child">
<Child handleTabs={this.handleTabs} />
</Tab>
)
}
}
// Child Component
import React from 'react';
import * as Survey from "survey-react";
var surveyValueChanged = function (sender, options) {
saveSurveyData(survey);
};
// critical surveyjs function
function saveSurveyData(survey) {
var data = survey.data;
//need to call handleTabs() (parent) in this function which is outside of Child Component Class
//handleTabs={this.handleTabs}
this.handleTabs(); // HOW ?
}
class Child extends React.Component {
constructor(props){
super(props);
}
render()
{
return(
<Survey.Survey model={survey}
onValueChanged={surveyValueChanged} />
)
}
}
我一直在尝试 ref、props 和 state - 我只是不明白如何在子组件之外执行此操作。
最佳答案
<Child keyName={this.handleTabs} />
在父组件中,您将其作为 Prop 传递(handleTabs是父组件中的方法) 现在要访问子组件中的任何 props 值,您可以直接使用(我已经更改了键名,以便您可以有清晰的概念)
//你想使用handleTabs(因为它是基于类的组件,所以使用这个关键字)
this.props.KeyName();
此外,您不需要在父组件中绑定(bind)句柄选项卡,因为您创建了不需要绑定(bind)的箭头函数。 对于普通函数,您需要绑定(bind) this。(因此绑定(bind)您的子函数)
import React from 'react';
import * as Survey from "survey-react";
class Child extends React.Component {
constructor(props){
super(props);
this.saveSurveyData = this.saveSurveyData.bind(this);
this.surveyValueChanged = this.surveyValueChanged.bind(this);
}
surveyValueChanged(sender, options) {
this.saveSurveyData(survey);
};
saveSurveyData(survey) {
var data = survey.data;
this.props.handleTabs();
console.log(this.props.handleTabs())
}
render()
{
return(
<Survey.Survey model={survey}
onValueChanged={this.surveyValueChanged} />
)
}
}
关于javascript - React - 从子组件外部调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59169653/