无需单击即可将数据传递给父级

时间:2019-07-01 14:47:19

标签: reactjs parent-child parent

我刚刚开始学习ReactJS,我需要一些帮助。我正在尝试将数据从子级发送到父级组件,而在子级中,我有此按钮代码

这是我的孩子

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";

class Locate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      city: "",
      countryName: ""
    };
  }

  componentDidMount() {
    axios
      .get("https://ipapi.co/json/")
      .then(response => {
        let data = response.data;
        this.setState({
          city: data.city,
          countryName: data.country_name
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <p> Country Name: {this.state.countryName} </p>
        <button onClick={() => { this.props.updateCity(this.state.city)}}>My city</button>
      </div>
    );
  }
}

export default Locate;

这是我的父母

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import Locate from "./location.js"


class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {

    };
  }

updateCity = (value) => {
   this.setState({ city: value });
}

  render() {
    return (
      <div>

        <Locate updateCity={this.updateCity} />

      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

一切正常,但是我需要传递this.state.city而没有按钮onClick函数。该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以在组件中创建自己的函数,并在需要时在应用程序流中随意调用该函数。

例如

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";

class Locate extends React.Component {
...
  myFunction() {
   this.props.updateCity(this.state.city)
  }

  componentDidMount() {
    // example calling it on didMount 
    this.myFunction();
  }
....
}

如果您需要在父母与孩子之间共享数据,可以查看Context API,这可能对您有用