如何在React中添加搜索组件?

时间:2018-08-07 12:19:50

标签: reactjs redux react-router react-redux react-starter-kit

我正在将当前的应用程序转换为React,当前的ap正在使用jquery和PHP。

当前搜索栏

<ul class="token-input">
    <li class="token-">
        <input name="p"  type="password" autocomplete="new-password" value="" data-open="false" class="form-control" placeholder="password protected.">
    </li>
</ul>

反应头

import React from 'react';
import { FormattedMessage } from 'react-intl';

import styled from 'styled-components';
import A from './A';
import Img from './Img';
import NavBar from './NavBar';
import HeaderLink from './HeaderLink';
import messages from './messages';
import SearchBar from '../SearchBar';
import UserNavbar from '../UserNavbar';
import logoImage from './logo.png';
import backgroundImage from './bg.png';
import './Header.css';

const HeaderImage = styled.div`
  background-image: url(${backgroundImage});
`;

/* eslint-disable react/prefer-stateless-function */
class Header extends React.Component {
  render() {
    return (
      <header>
        <HeaderImage className="navbar navbar-primary bg-dark shadow-sm">
          <div className="container d-flex justify-content-between">
            <A
              to="/"
              className="navbar-brand d-flex align-items-center"
            >
              <Img src={logoImage} />
              <span className="slogan d-none d-md-block"> </span>
            </A>
            <SearchBar className="search-bar" />
            <UserNavbar />
          </div>
        </HeaderImage>

        <div className="tab-area">
          <A href="" />
          <NavBar>
            <HeaderLink to="/">
              <FormattedMessage {...messages.recent} />
            </HeaderLink>
          </NavBar>
        </div>
      </header>
    );
  }
}

export default Header;

谁能告诉我如何将该搜索字段作为1组件集成到标题中? (并且搜索是从网站正文中的过滤器内容中获取数据)

1 个答案:

答案 0 :(得分:0)

在SearchBar.js中:

class SearchBar extends React.Component {
  state = {
    value: '',
  }

  handleChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  }

  handleSubmit = () => {
    const { value } = this.state;

    // do ajax request or something in order
    // to submit and redirect to a different page
    // containing search results
  }

  render() {
    return (
      <ul class="token-input">
        <li class="token-">
          <input
            name="p"
            type="password"
            autocomplete="new-password"
            value={this.state.value}
            data-open="false"
            className="form-control"
            placeholder="password protected."
          />
        </li>
      </ul>
    );
  }
}

然后,您只需要以相同的方式导入即可。