设置子组件的状态并将其通过Context API传递给父组件

时间:2020-07-31 17:29:34

标签: reactjs context-api

我有一个有状态的应用程序组件,其任务是获取数据。它要获取的数据基于用户在输入字段中键入的内容。输入字段位于包装在组件中的另一个组件中,而App组件包装在该组件中。

如何将数据从输入字段传递到Search.js中的onSearch函数? App.js

class App extends Component {
  state = {
    images: [],
    value: '',
  };

  onSearch = (query) => {
    axios
      .get(
        `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${query}&per_page=24&format=json&nojsoncallback=1`
      )
      .then((res) => {
        this.setState({
          images: res.data.photos.photo,
        });
      })
      .catch((err) => {
        console.log('There was an error while trying to fetch the data: ', err);
      });
  };

  render() {
    return (
      <Provider
        value={{
          images: this.state.images,
          actions: {
            onSearch: this.onSearch,
          },
        }}
      >
        <BrowserRouter>
          <div className='container'>
            <Header />
            <PhotoList />
          </div>
        </BrowserRouter>
      </Provider>
    );
  }
}

Search.js

<Consumer>
      {(context) => {
        const handleChange = (e) => {
          context.value(e.target.value);
        };

        const handleSubmit = (e) => {
          e.preventDefault();
          context.actions.onSearch();
          e.currentTarget.reset();
        };

        return (
          <form className='search-form' onSubmit={handleSubmit}>
            <input
              type='search'
              name='search'
              placeholder='Search'
              required
            />
            <button type='submit' className='search-button'>
              <svg
                fill='#fff'
                height='24'
                viewBox='0 0 23 23'
                width='24'
                xmlns='http://www.w3.org/2000/svg'
              >
                <path d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z' />
                <path d='M0 0h24v24H0z' fill='none' />
              </svg>
            </button>
          </form>
        );
      }}
    </Consumer>

0 个答案:

没有答案