简体   繁体   English

将子组件的状态传递给父组件?

[英]Passing the state of a Child component to a Parent?

I think I know what I need to do to make my searchLocationChange function work, but I'm not sure quite how to do it. 我想我知道我需要做些什么来使我的searchLocationChange函数工作,但我不知道该怎么做。 Please forgive the indentation, was grappling a fair bit with StackOverflow's WYSIWYG! 请原谅缩进,正在与StackOverflow的WYSIWYG进行斗争!

Here's my Parent component setup: 这是我的父组件设置:

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

With this specific function I want to make work: 有了这个特定的功能,我想做一些工作:

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

And in my Child component, the logic is: 在我的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>
        );
    }
}

I realise I'm trying to update the Parent component with searchText from the state of the Child component, but I can't figure out what I need to change to make this work. 我意识到我正在尝试使用来自Child组件状态的searchText更新Parent组件,但我无法弄清楚我需要更改以使其工作。 I have a sneaking suspicion I'm 99% of the way there, and it's only a few more lines I need, but I could be way off? 我有一种偷偷摸摸的怀疑,我99%的路在那里,而且我只需要几条线,但我可能会离开?

You're already passing down searchLocationChange from your parent. 您已经从父级传递了searchLocationChange

in parent component: 在父组件中:

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

in child: 在孩子:

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

You should call the function like that this.props.searchLocationChange(this.state.searchText) 你应该像这样调用函数this.props.searchLocationChange(this.state.searchText)

You can do something like below 你可以做下面这样的事情

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

and function definition should be 和函数定义应该是

searchLocationChange(searchText) {

You are mixing controlled and uncontrolled. 你是混合控制和不受控制的。 Either do controlled or uncontrolled. 要么是受控制的,要么是不受控制的。 So take the search Text from parent only. 因此,仅从父级搜索文本。 Above solutiion is one way of doing this . 以上解决方案是这样做的一种方式。 Another way is to pass searchTxt from parent to child. 另一种方法是将searchTxt从父级传递给子级。

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

Move your handleInputChange in parent: 在父级中移动handleInputChange:

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

Then change your child component respective line to 然后将您的子组件各自更改为

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

Now when you try the above code it should work. 现在当你尝试上面的代码时,它应该工作。 Now you are keeping your searchTxt in the parent component. 现在,您将searchTxt保留在父组件中。 your SearchForm component is Completely controlled now. 您的SearchForm组件现在已完全控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将状态从子级传递到父组件 - Passing state from a child to parent component React,将状态从子组件传递给父组件 - React, passing state from a Child component to the Parent 在 React 中将状态从子组件传递到父组件? - Passing a state from child component to parent component in React? 将 state 从子组件传递到 Wordpress Gutenberg Sidebar 中的父组件 - Passing state from child component to parent component in a Wordpress Gutenberg Sidebar 将 state 传递给父母,然后传递给孩子 - Passing state to parent and then to child 将状态传递给父组件 - Passing state to parent component 将handleSubmit()传递给子组件不会修改父组件的状态 - Passing handleSubmit() to child component does not modify parent's state React:无法通过将函数传递给更新它的子组件来更新父状态 - React: unable to update parent state by passing function to child component that updates it 将 state 从父函数传递给子函数 React 组件 - Passing state from parent to child functional React Component React:子组件正在将其状态传递给父组件,但是一旦父组件拥有它,父组件就不会更新其状态 - React: Child component is passing it's state up to parent, but once parent has it, the parent is not updating its state
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM