Calling a function in React

前端 未结 6 1968
感动是毒
感动是毒 2021-02-04 21:55

I\'m a beginner in React, and I\'m a little confused about calling a function in React.

I saw the following ways and I don\'t know when to use each and which one.

<
6条回答
  •  滥情空心
    2021-02-04 22:29

    this is correct -> handleAddTodo ={this.handleAddTodo} When function passing to child component you have to bind your function like this handleAddTodo ={this.handleAddTodo.bind(this)}. below code help out your doubt.

    Simple Example

    import React from 'react';
    
    class App extends React.Component {
    
       constructor(props) {
          super(props);
    
          this.state = {
             data: 'Initial data...'
          }
    
          this.updateState = this.updateState.bind(this);
    
       };
    
       updateState() {
          this.setState({data: 'Data updated...'})
       }
    
       render() {
          return (
             

    {this.state.data}

    ); } } export default App;

    Child Events

    import React from 'react';
    
    class App extends React.Component {
    
       constructor(props) {
          super(props);
    
          this.state = {
             data: 'Initial data...'
          }
    
          this.updateState = this.updateState.bind(this);
       };
    
       updateState() {
          this.setState({data: 'Data updated from the child component...'})
       }
    
       render() {
          return (
             
    ); } } class Content extends React.Component { render() { return (

    {this.props.myDataProp}

    ); } } export default App;

    Refer here

提交回复
热议问题