如何在React中将函数作为props传递?

5
我有一个函数式组件GetWeather,我想将GetLocation函数的结果作为属性传递给它,根据这个属性,GetWetaher将执行另一个get请求(在下面的示例中,它只呈现其属性)。我认为这必须发生在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> 
        );
      }
    }

更新: 根据下面 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> 
    );
  }
}

1
你能否更详细地描述你的问题,因为它对我来说有点模糊。但是从我目前的理解来看,你可以在LocalWeather组件构造函数中创建一个默认状态,然后在componentDidMount中调用获取位置的方法,并将返回值设置为LocalWeather组件。之后,您可以通过LocalWeather组件的状态将位置作为props传递给GetWeather组件。 - theterminalguy
我认为你理解了我的问题...现在它对我有效;) - irom
1个回答

5

You can do it alternatively also

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> 
    );
  }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接