我的第一个反应课是:
import React from 'react';
class School extends React.Component {
render() {
return (
<div className="navigator" ref={(input) => { this.schoolref = input; }}>
<div className="pan ui-draggable" style={this.props.subNavDimension} />
</div>
);
}
}
export default School;
我的第二个React类是:
import React from 'react';
class College extends React.Component {
showshool = () => {
//Here I want to access the ref defined in School class.
}
render() {
return (
<div className="ui-college-hello">
<section className="1" onClick={this.showschool}></section>
<section className="2" onClick={this.showstudent}></section>
</div>
);
}
}
export default College;
上述两个类的父类是:
import React from 'react';
import School from 'School';
import College from 'College';
class ParentClass extends React.Component {
showshool = () => {
//Here I want to access the ref defined in School class.
}
render() {
return (
<School />
<College />
);
}
}
export default ParentClass;
我基本上试图访问另一个组件的div的ref。我不能使用redux商店。请帮帮我。
答案 0 :(得分:1)
父:
import React from 'react';
import School from 'School';
import College from 'College';
class ParentClass extends React.Component {
setRef = myComponent => this.myComponent = myComponent
showshool = () => {
// use this.myComponent
}
render() {
return (
<School setRef={this.setRef} />
<College ref={this.myComponent }/>
);
}
}
export default ParentClass;
学院
import React from 'react';
class College extends React.Component {
showshool = () => {
// this.props.ref
}
render() {
return (
<div className="ui-college-hello">
<section className="1" onClick={this.showschool}></section>
<section className="2" onClick={this.showstudent}></section>
</div>
);
}
}
export default College;
学校:
import React from 'react';
class School extends React.Component {
componentDidMount() {
this.props.setRef(this.schoolref);
}
render() {
return (
<div className="navigator" ref={(input) => { this.schoolref = input; }}>
<div className="pan ui-draggable" style={this.props.subNavDimension} />
</div>
);
}
}
export default School;