【发布时间】:2020-03-28 21:07:18
【问题描述】:
我想从类函数外部获取子组件文件
函数 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 - 我只是不明白如何在子组件之外执行此操作。
【问题讨论】:
-
如果
handleTabs仅具有通用的 Javascript 功能,您可以将其移出组件。如果它具有特定于 React 的功能(例如调用setState),那么您必须将它从子函数传递给函数,并继续传递它,例如:onValueChanged={(sender, options) => surveyValueChanged(sender, options, this.props.handleTabs)}等等,直到它到达需要的地方 -
handleTabs 确实有(需要)setState - 但是等等,看起来你说 this.props.handleTabs 会在孩子中设置......但是我如何从父母那里传下来- 你能给我一个答案吗/example thx
-
surveyValueChanged被构建到一个surveyjs代码中,并且它在类组件之外 - 所以this.props ...它根本不喜欢
标签: javascript reactjs babeljs jsx