我想从类函数外部获取子组件文件
函数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-我只是不了解如何在子组件之外执行此操作。
答案 0 :(得分:1)
handleTab传递给this.props。您应该将surveyValueChanged并将saveSurveyData保存到子组件。
示例:
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
import React from 'react';
import * as Survey from "survey-react";
class Child extends React.Component {
constructor(props){
super(props);
}
surveyValueChanged = (sender, options) => {
this.saveSurveyData(survey);
};
// critical surveyjs function
saveSurveyData = (survey) => {
var data = survey.data;
this.props.handleTabs();
}
render()
{
return(
<Survey.Survey model={survey}
onValueChanged={this.surveyValueChanged} />
)
}
}
答案 1 :(得分:0)
<Child keyName={this.handleTabs} />
在父组件中,您将其作为道具传递(handleTabs是父项中的方法) 现在,您可以直接使用Child组件中的任何props值(我更改了键名,以便您有清晰的概念)
//您要使用handleTabs(由于它是基于类的组件,因此请使用此关键字)
this.props.KeyName();
您还不需要在父组件中绑定句柄选项卡,因为您创建了不需要绑定的箭头函数。 对于正常功能,您需要将此绑定。(因此请绑定您的子功能)
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} />
)
}
}