![](/img/trans.png)
[英]Unable to call parent component function from child component in React
[英]React - Call Parent function from OUTSIDE of Child Component
我想从类函数外部获得子组件文件
函数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} />
在父组件中,您将其作为道具传递(handleTabs 是父中的一个方法)现在可以直接使用子组件中的任何道具值访问(我已经更改了键名,以便您可以有清晰的概念)
//你想使用handleTabs(因为它是基于类的组件使用这个关键字)
this.props.KeyName();
此外,您不需要在父组件中绑定句柄选项卡,因为您创建了一个不需要绑定的箭头函数。 对于普通函数,你需要绑定 this。(所以绑定你的子函数)
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} /> ) } }
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} />
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.