山有木兮木有枝,心悦君兮君不知。
通过子组件传过来的组件实例. 父组件在去调用子组件的方法
父组件
import React, { Component } from 'react';
import Login from '@/components/Login';
import Logout from '@/components/Logout';
import { Button } from 'antd';
class Index extends Component {
state = {
tableList: [],
isLogin: true,
login: '',
logout: '',
};
getSonFn = () => {
this.state.login.getList();
}
onRef = (val, ref) => {
console.log(val, ref);
switch (val) {
case 'login':
this.state.login = ref
break;
case 'logout':
this.state.logout = ref
break;
default:
break;
}
}
render() {
return (
<div className="shadow-radius">
<Button type="primary" onClick={ this.getSonFn } className="mr20">调子组件方法</Button>
<Button type="primary" onClick={ this.chageData } className="mr20">子组件给父组件传值</Button>
<Login onRef={this.onRef}/>
<div/>
);
}
}
export default Index;
子组件
import React from 'react';
class Login extends React.Component {
getList = () => {
console.log('这是子组件');
}
componentWillMount() {
this.props.onRef('login', this);
}
render() {
return <div>login</div>
}
}
export default Login;