【发布时间】:2018-07-17 22:32:46
【问题描述】:
如何从父组件调用子组件函数?我试过使用 refs 但我无法让它工作。我收到诸如无法读取未定义的属性“handleFilterByClass”之类的错误。
路径:Parent Component
export default class StudentPage extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
newStudentUserCreated() {
console.log('newStudentUserCreated1');
this.refs.studentTable.handleTableUpdate();
}
render() {
return (
<div>
<StudentTable
studentUserProfiles={this.props.studentUserProfiles}
ref={this.studentTable}
/>
</div>
);
}
}
路径:StudentTable
export default class StudentTable extends React.Component {
constructor(props) {
super(props);
this.state = {
studentUserProfiles: props.studentUserProfiles,
};
this.handleTableUpdate = this.handleTableUpdate.bind(this);
}
handleTableUpdate = () => (event) => {
// Do stuff
}
render() {
return (
<div>
// stuff
</div>
);
}
}
更新
路径StudentContainer
export default StudentContainer = withTracker(() => {
const addStudentContainerHandle = Meteor.subscribe('companyAdmin.addStudentContainer.userProfiles');
const loadingaddStudentContainerHandle = !addStudentContainerHandle.ready();
const studentUserProfiles = UserProfiles.find({ student: { $exists: true } }, { sort: { lastName: 1, firstName: 1 } }).fetch();
const studentUserProfilesExist = !loadingaddStudentContainerHandle && !!studentUserProfiles;
return {
studentUserProfiles: studentUserProfilesExist ? studentUserProfiles : [],
};
})(StudentPage);
【问题讨论】:
-
你想完成什么?将
studentUsers作为道具传递给StudentTable可能是一个更好的主意,而不是尝试在子组件中调用函数。 -
哦,我已经把 studentUsers 作为道具传下来了。基本上,另一个组件正在插入一个新的 studentUser。发生这种情况时,我需要告诉表进行更新,这样新的 studentUser 就会出现,而无需重新加载页面。
-
好的。如果另一个组件正在更新
studentUsers,那么它应该自动更新组件树。你怎么更新studentUsers? -
你的意思是在 StudentTable 组件中?
-
我在考虑树上的组件,
StudentPage的父级更新studentUserProfiles。
标签: reactjs