Reputation: 61
class AUsers extends React.Component {
constructor(props) {
super(props);
this.list = React.createRef();
}
handleChangeDataList = () => {
this.list.current.reloadAUserTable();
}
render(){
return(
<AUserList
ref={(ref) => { this.list = ref; }}
/>
<Button onClick={() => this.handleChangeDataList()}>atest</Button>
)
}
}
class AUserList extends React.Component {
reloadAUserTable = () => {
console.log('good');
}
}
But after click the button, I met this error
What is wrong?
Upvotes: 1
Views: 105
Reputation: 2860
React is unidirectional
it means you cannot access a method from the child component into your parent component ( it's not a good practice ) but what you can do is to place reloadAUserTable()
inside the parent component and pass the reference has a prop.
This is also called Level-up
class AUsers extends React.Component {
constructor(props) {
super(props);
this.list = React.createRef();
}
handleChangeDataList = () => {
this.list.current.reloadAUserTable();
}
reloadAUserTable = () => {
console.log('good');
}
render(){
return(
<AUserList
ref={(ref) => { this.list = ref; }}
/>
<Button onClick={() => this.handleChangeDataList()}>atest</Button>
)
}
}
Now pass it has a prop
then, this way your parent component will have easy access to the method and also child component can access it through the props been passed.
Upvotes: 1