将孩子的状态传给父母

时间:2019-11-12 20:01:46

标签: reactjs

我有一个子组件(搜索),我正在尝试将lat&lng的状态传递到父项的状态。

class Search extends React.Component {
    constructor(props) {
      super(props);

      this.state = {

        lat: '',
        lng: ''
      };

      this.handleSubmit = this.handleSubmit.bind(this)

    }

    handleSubmit = (event) => {
      const addressObject = this.autocomplete.getPlace();

        this.setState(
          {
            lat: addressObject.geometry.location.lat(),
            lng: addressObject.geometry.location.lng(),
          }
        );

    }

    render() {
        return (
          <div>

            <div className = 'search-box'>
            <form onSubmit = {this.handleSubmit}>
              <input className = 'search-text'type = 'textbox' id="autocomplete" placeholder="Type your city"  
              />
              <button> submit</button>

            </form>

            </div>
          </div>
        );
      }
}

我正在尝试更改父母的经/纬度状态,使其等于孩子的状态

class Display extends React.Component{
    constructor () {
        super()
        this.state = {
            lat: '{child's state}', ??
            lng: '{child's state}',??

        }
    }
render () {
        return (
            <div>
                <SearchBar />
                <WeatherDisplay 
                    data = {this.state}
                />
            </div>
        )
    }
}

我该怎么办?后续问题是,这种不良反应是否会引起反应?

1 个答案:

答案 0 :(得分:0)

在父组件中创建一个函数,并将其作为道具传递给子组件。喜欢:

子组件:

class Search extends React.Component {

    handleSubmit = (event) => {
      const addressObject = this.autocomplete.getPlace();
        this.props.update(
          {
            lat: addressObject.geometry.location.lat(),
            lng: addressObject.geometry.location.lng(),
          }
        );

    }

    render() {
        return (
          <div>
            <Script
              url="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnqBcICpcIUF4OcyIjqIEoIMXYOXqZnG8&libraries=places"
              onLoad={this.handleScriptLoad}
            />
            <div className = 'search-box'>
            <form onSubmit = {this.handleSubmit}>
              <input className = 'search-text'type = 'textbox' id="autocomplete" placeholder="Type your city"  
              />
              <button> submit</button>

            </form>

            </div>
          </div>
        );
      }
  }

父组件:

class Display extends React.Component{
    constructor () {
        super()
        this.state = {
            lat: null,
            lng: null

        }
    }
    update=({lat,lng})=>{
      this.setState({
        lat,
        lng
      })
    }
    render () {
        return (
            <div>
                <SearchBar update={this.update}/>
                <WeatherDisplay 
                    data = {this.state}
                />
            </div>
        )
    }
}