How to access method of the child component from parent in reactjs

你。 提交于 2021-01-29 17:47:59

问题


I'm trying to call child component from parent component in reactjs using refs.but it throws error saying showModal() is not a function when I tried to call.

//app.js

 class app extends Component {
      constructor(props) {
         super(props);

         this.POPUP = React.createRef();
      }
      showModal(){
            this.POPUP.showModal(true);
      }
      render() {
         return (
             <React.Fragment>
                <span><a onClick={() => this.showModal()}>Show</a></span>

                <POPUP onRef={ref => (this.POPUP = ref)}></POPUP>
             </React.Fragment >
       )
     }
 }

popup.js

 class POPUP extends Component {
   showModal(show) {
         console.log('showmodal');

     }
   render() {
          console.log(this.props.showModalPopup);
       <React.Fragment>
             <Modal

                 position="center">
                 <div>
                     //code
                 </div>
             </Modal>
       </React.Fragment>
       )
     }
 }

Is there any alternative in nextjs.please help


回答1:


https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs

First of all if you want to access that POPUP instance you should do

this.POPUP.current.showModal(true);

BTW Your showModal function needs to be bound to the child component if you intend to alter its state.

However, even this is doable - this is usually not the recommended way of doing React.

If you want the parent to decide if showModalPopup should be true, you probably should keep the state inside of your parent component:

 class App extends Component {
      constructor(props) {
         super(props);

         this.state = { showModalPopup: false };

         this.showModal = this.showModal.bind(this);
      }
      showModal(){
            this.setState({ showModalPopup: true });
      }
      render() {
         return (
             <React.Fragment>
                <span><a onClick={this.showModal}>Show</a></span>

                <POPUP show={this.state.showModalPopup}></POPUP>
             </React.Fragment >
       )
     }
 }
const POPUP = ({ show }) => (
    <Modal show={show} position="center">
      // your content.
    </Modal>
)



来源:https://stackoverflow.com/questions/57955390/how-to-access-method-of-the-child-component-from-parent-in-reactjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!