如何在React中传递函数作为道具?

iro*_*rom 5 reactjs

我有功能组件GetWeather,我希望将GetLocation函数的结果作为道具传递,基于GetWetaher将执行某些操作,即另一个获取请求(在下面的示例中,它仅渲染其道具).我认为它必须在ComponentDidMount内部发生,不知道如何做到这一点

    function GetLocation() {
        axios.get('http://ipinfo.io')
          .then((res) => {      
            return res.data.loc;
          })

      }
    function GetWeather(props) {
    //more code here, including another get request, based on props
        return <h1>Location: {props.location}</h1>;    
    }

    class LocalWeather extends Component {           
      componentDidMount() {    
        //???     
      }          
      render() {
        return (
          <div >                         
                <GetWeather location={GetLocation}/> //???                                               
          </div> 
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)

更新:所以根据Damian的建议,下面的内容对我有用

function GetWeather(props) {   
    return <h3>Location: {props.location}</h3>;   
}

class LocalWeather extends Component {
  constructor(props) {
    super(props);
    this.state = {
      location: []
    }; 
  }
  getLocation() {
    axios.get('http://ipinfo.io')
      .then((res) => {       
        this.setState({location:res.data.loc});        
      })         
  }

  componentDidMount() {    
    this.getLocation();     

  }
  render() {
    return (
      <div >                       
            <GetWeather location={this.state.location}/>                                                 
      </div> 
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Vik*_*ini 5

你也可以这样做

constructor() {
  super();
  this.state = {
    Location:[]
  }
}

function GetLocation() {
  axios.get('http://ipinfo.io').then((res) => { 
    this.setState ({
      Location:res.data.loc;
    });
  });
}

function GetWeather(props) {
  return <h1>Location: {this.props.location}</h1>;    
}
    
class LocalWeather extends Component {           
  componentDidMount() {    
    //code     
  }          

  render() {
    return (
      <div >                         
        <GetWeather location={this.GetLocation.bind(this)}/>                                            
      </div> 
    );
  }
}
Run Code Online (Sandbox Code Playgroud)