【问题标题】:Passing the state of a Child component to a Parent?将子组件的状态传递给父组件?
【发布时间】:2019-04-02 11:52:14
【问题描述】:

我想我知道我需要做什么才能使我的searchLocationChange 功能正常工作,但我不确定该怎么做。请原谅缩进,在 StackOverflow 的 WYSIWYG 上有点挣扎!

这是我的父组件设置:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            forecasts: [],
            location: {
                city: '',
                country: '',
            },
            selectedDate: 0,
            searchText: '',
        };
        this.handleForecastSelect = this.handleForecastSelect.bind(this);
        this.searchLocationChange = this.searchLocationChange.bind(this);
    }
}

我想通过这个特定的功能来工作:

searchLocationChange() {
    console.log(this.state.searchText);
    Axios.get('https://mcr-codes-weather.herokuapp.com/forecast', {
            params: {
                city: this.state.searchText,
            },
        })
        .then((response) => {
            this.setState({
                forecasts: response.data.forecasts,
                location: {
                    city: response.data.location.city,
                    country: response.data.location.country,
                }
            });
        });
}

而在我的 Child 组件中,逻辑是:

class SearchForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: '',
        };
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange(event) {
        const enteredText = event.target.value;
        this.setState({
            searchText: enteredText
        });
    }

    render() {
        return (
            <span className="search-form">
              <div className="search-form__input"><input type="text" value={this.state.searchText} onChange={this.handleInputChange} /></div>
              <div className="search-form__submit"><button onClick={this.props.searchLocationChange}>Search</button></div>
            </span>
        );
    }
}

我意识到我正在尝试使用来自子组件状态的 searchText 更新父组件,但我无法弄清楚我需要更改哪些内容才能使其正常工作。我有一个偷偷摸摸的怀疑,我已经完成了 99% 的路,而且我只需要多几行,但我可能会走得很远?

【问题讨论】:

    标签: reactjs components state


    【解决方案1】:

    你应该像this.props.searchLocationChange(this.state.searchText)那样调用函数

    您可以执行以下操作

     <div className="search-form__submit"><button onClick={() => {this.props.searchLocationChange(this.state.searchText)}}>Search</button></div>
    

    函数定义应该是

    searchLocationChange(searchText) {
    

    【讨论】:

    • 非常感谢 - 非常感谢!
    【解决方案2】:

    您正在混合受控和不受控。要么受控,要么不受控。因此,仅从父级获取搜索文本。以上解决方案是这样做的一种方法。另一种方法是将 searchTxt 从父级传递给子级。

    <SearchForm 
       searchTxt={this.state.searchTxt}
       handleInputChange={this.handleInputChange}
       searchLocationChange={this. searchLocationChange}
    />
    

    将您的 handleInputChange 移到父项中:

    handleInputChange = (event) => {
        const enteredText = event.target.value;
        this.setState({ searchText: enteredText });
      }
    

    然后将您的子组件相应的行更改为

     <div className="search-form__input"><input type="text" value={this.props.searchText} onChange={this.props.handleInputChange} /></div>
    

    现在,当您尝试上面的代码时,它应该可以工作了。现在您将 searchTxt 保留在父组件中。您的 SearchForm 组件现在已完全受控。

    【讨论】:

    • 非常感谢您的帮助 - 非常感谢。
    【解决方案3】:

    你已经从你的父母那里继承了searchLocationChange

    在父组件中:

    searchLocationChange(searchedText) {
    console.log(searchText);
    Axios.get('https://mcr-codes-weather.herokuapp.com/forecast', {
      params: {
        city: searchText,
      },
    })
      .then((response) => {
        this.setState({
          forecasts: response.data.forecasts,
          location: {
            city: response.data.location.city,
            country: response.data.location.country,
          },
        });
      });
    }
    

    在孩子中:

    render() {
     const { searchText } = this.state;
        return (
          <span className="search-form">
            <div className="search-form__input"><input type="text" value={this.state.searchText} onChange={this.handleInputChange} /></div>
            <div className="search-form__submit"><button onClick={()=>{this.props.searchLocationChange(searchText)}}>Search</button></div>
    
          </span>
        );
      }
    

    【讨论】:

    • 您正在调用 onclick searchLocation 中的函数。将其更改为 onClick={() => this.props.searchLocationChange(searchText)}
    • @simbathesailor 感谢您指出这一点。从字面上看,我错过了。
    猜你喜欢
    • 2019-02-17
    • 2022-07-15
    • 2014-12-18
    • 2019-08-15
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2020-07-04
    • 2017-05-31
    相关资源
    最近更新 更多